writing to excel file with text template in C#

1.4k Views Asked by At

I want to write a template file (*.tt) to write data to an XLS file in C#. How can I write the data in separate columns? For example I want to an excel file with 3 column as below

column1   column2   column3
sss         ttt       rrr
www         qqq        aaa

but I can't insert them in separate column

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

and the output in excel file is like this

column1
sss ttt rrr
www qqq aaa

and all data are inserted at the first column

1

There are 1 best solutions below

0
On

If you opt for using Excel Interop, then following is a demonstration of putting data in separate columns of an Excel worksheet. You can refer this for more details on Excel Object model reference.

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);

        }
    }
}