C# 用C语言编写文本模板到excel文件#
我想编写一个模板文件(*.tt),将数据写入C#中的XLS文件。如何在单独的列中写入数据? 例如,我想创建一个包含3列的excel文件,如下所示C# 用C语言编写文本模板到excel文件#,c#,excel,texttemplate,C#,Excel,Texttemplate,我想编写一个模板文件(*.tt),将数据写入C#中的XLS文件。如何在单独的列中写入数据? 例如,我想创建一个包含3列的excel文件,如下所示 column1 column2 column3 sss ttt rrr www qqq aaa 但我不能将它们插入单独的列中 <#= "sss " #><#= "ttt " #><#= "," #><#= "rrr" #> <#=
column1 column2 column3
sss ttt rrr
www qqq aaa
但我不能将它们插入单独的列中
<#= "sss " #><#= "ttt " #><#= "," #><#= "rrr" #>
<#= "www " #><#= "qqq " #><#= "," #><#= "aaa" #>
如果您选择使用Excel Interop,则所有数据都将插入第一列,下面是将数据放入Excel工作表的单独列中的演示。有关Excel对象模型参考的更多详细信息,请参阅
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelInterop
{
class Program
{
static void Main(string[] args)
{
Excel.Application xlApp = null;
Excel.Workbook xlWorkBook = null;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add();
Excel.Worksheet newWorksheet = null;
newWorksheet = (Excel.Worksheet)xlApp.Application.Worksheets.Add();
xlApp.ScreenUpdating = false;
Excel.Range excelRange = newWorksheet.UsedRange;
// Column 1
excelRange.Cells.set_Item(1, 1, "Column 1");
// Column 1 Data
excelRange.Cells.set_Item(2, 1, "sss");
// Column 2
excelRange.Cells.set_Item(1, 2, "Column 2");
// Column 1 Data
excelRange.Cells.set_Item(2, 2, "ttt");
// Save it as .xls
newWorksheet.SaveAs("D:\\ExcelInterop", Excel.XlFileFormat.xlExcel7);
// Clean up
xlWorkBook.Close();
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
}
}
}
定义rage,然后使用循环使用此范围对象在不同列中插入值。@user3217843 rage是什么,我应该如何定义它?@fasadat您当前使用什么机制在C#中创建XLS文件?@MNS:我编写了一个文本模板file@fasadat我建议使用C#使用Excel互操作。你几乎可以做任何你想做的事。
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelInterop
{
class Program
{
static void Main(string[] args)
{
Excel.Application xlApp = null;
Excel.Workbook xlWorkBook = null;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add();
Excel.Worksheet newWorksheet = null;
newWorksheet = (Excel.Worksheet)xlApp.Application.Worksheets.Add();
xlApp.ScreenUpdating = false;
Excel.Range excelRange = newWorksheet.UsedRange;
// Column 1
excelRange.Cells.set_Item(1, 1, "Column 1");
// Column 1 Data
excelRange.Cells.set_Item(2, 1, "sss");
// Column 2
excelRange.Cells.set_Item(1, 2, "Column 2");
// Column 1 Data
excelRange.Cells.set_Item(2, 2, "ttt");
// Save it as .xls
newWorksheet.SaveAs("D:\\ExcelInterop", Excel.XlFileFormat.xlExcel7);
// Clean up
xlWorkBook.Close();
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
}
}
}