0

我想编写一个模板文件 (*.tt) 以将数据写入 C# 中的 XLS 文件。如何将数据写入单独的列?例如,我想要一个 3 列的 excel 文件,如下所示

column1   column2   column3
sss         ttt       rrr
www         qqq        aaa

但我不能将它们插入单独的列

<#= "sss " #><#= "ttt " #><#= "," #><#= "rrr" #>
<#= "www " #><#= "qqq " #><#= "," #><#= "aaa" #>

excel文件中的输出是这样的

column1
sss ttt rrr
www qqq aaa

并且所有数据都插入到第一列

4

1 回答 1

0

如果您选择使用 Excel 互操作,则以下是将数据放在 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);

        }
    }
}
于 2014-12-01T09:45:56.930 回答