如何从C#导出时格式化excel单元格

时间:2016-04-13 07:24:28

标签: c# .net excel winforms datatable

我写了一个程序,用C#中的数据表导出excel。默认情况下,单元格格式已在常规中修复。如何通过程序更改单元格格式? (示例格式:文字,数字)。 这是我的代码

        private void WriteExcel(DataTable datatable, string FileName)
        {
            StringBuilder SBuild = new StringBuilder();
            using (StreamWriter sw2Excel = File.CreateText(FileName))
            {
                //get the Columns of the DataTable in the 1st Line
                for (int i = 0; i < datatable.Columns.Count; i++)
                {
                    SBuild.Append(datatable.Columns[i].ColumnName + "\t");
                }
                sw2Excel.WriteLine(SBuild.ToString());
                //Fill The Rows To the Excel File
                for (int i = 0; i < datatable.Rows.Count; i++)
                {
                    StringBuilder swRowSb = new StringBuilder();
                    for (int k = 0; k < datatable.Columns.Count; k++)
                    {
                        swRowSb.Append(datatable.Rows[i][k].ToString().Replace(',', ' ') + "\t");
                    }
                    sw2Excel.WriteLine(swRowSb.ToString());
                }
                Microsoft.Office.Interop.Excel.ApplicationClass app = new Microsoft.Office.Interop.Excel.ApplicationClass();
                Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, ",", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                workBook.SaveAs(FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing
                , Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                app.Workbooks.Close();
                app.Quit();
            }
        }

1 个答案:

答案 0 :(得分:0)

关于Excel格式here

的文章很好

建议对代码进行更改 - 请注意以下代码未经测试且基于文章

Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets.get_Item(1);

Microsoft.Office.Interop.Excel.Worksheet.Range cellRange = workSheet.get_Range("a1", "z256")

//change to text format
cellRange.NumberFormat = "@";