日期:2014-05-18  浏览次数:21284 次

C# DataTable导出到EXCEL保存多个SHEET
由于以前用惯了IO导出EXCEL,但是这次被告知要保存多个SHEET,只能用COM组件,但是翻了下
材料,找不到如何保存多个SHEET的方法,最简单的方法如下
C# code

    int columnCount = dt.Columns.Count;
            int columnCount2 = dt2.Columns.Count;
            int columnCount3 = dt3.Columns.Count;

            //创建Excel对象
            Microsoft.Office.Interop.Excel._Application excelApp = new ApplicationClass();
            //新建工作簿
            Microsoft.Office.Interop.Excel._Workbook workBook = excelApp.Workbooks.Add(true);
            //新建工作表
            Microsoft.Office.Interop.Excel._Worksheet worksheet = workBook.ActiveSheet as Microsoft.Office.Interop.Excel._Worksheet;
            Microsoft.Office.Interop.Excel._Worksheet worksheet2 = workBook.ActiveSheet as Microsoft.Office.Interop.Excel._Worksheet;
            Microsoft.Office.Interop.Excel._Worksheet worksheet3 = workBook.ActiveSheet as Microsoft.Office.Interop.Excel._Worksheet;

            
            //设置表头
            for (int i = 0; i < columnCount; i++)
            {
                Range headRange = worksheet.Cells[2, i + 1] as Range;//获取表头单元格
                headRange.Value2 = dt.Columns[i].Caption;//设置单元格文本
            }
          

            //填充数据
            for (int i = 0; i < dt.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    Range contentRange = worksheet.Cells[i + 3, j + 1] as Range;//获取单元格
                    contentRange.Value2 = dt.Rows[i][j].ToString().Trim();//设置单元格文本
                }
            }
           

            //保存导出的Excel
            
            string fileName = "E:\\测试" + ".xls";
            workBook.SaveCopyAs(fileName);
            workBook.Saved = true;


 菜鸟求帮助,如何保存多个SHEET?


------解决方案--------------------
xlSheets = workBook.Sheets as Sheets; 

//添加 Sheet
xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing); 
xlNewSheet.Name = "xxx"; 

//填充
Range contentRange = xlNewSheet.Cells[i + 3, j + 1] as Range;//获取单元格
contentRange.Value2 = dt.Rows[i][j].ToString().Trim();//