【问题标题】:writing to excel file with text template in C#在 C# 中使用文本模板写入 excel 文件
【发布时间】:2015-01-29 02:58:15
【问题描述】:

我想编写一个模板文件 (*.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

所有数据都插入第一列

【问题讨论】:

  • 定义范围,然后使用循环使用此范围对象在不同列中插入值。
  • @user3217843 什么是愤怒,我应该如何定义它?
  • @fasadat 您目前使用什么机制在 C# 中创建 XLS 文件?
  • @MNS : 我写了一个文本模板文件
  • @fasadat 我建议使用 C# 使用 Excel 互操作。你几乎可以做任何你想做的事情。

标签: c# excel texttemplate


【解决方案1】:

如果您选择使用 Excel 互操作,则以下是将数据放在 Excel 工作表的单独列中的演示。您可以参考this 了解有关 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);

        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多