关于NPOI这里就不多介绍了,想必找到这篇文章的人都知道这个东西~ 下面直入主题!
int rowIndex = 2;         //从第二行开始,因为前两行是模板里面的内容 
        int colIndex = 0;


        DataTable table = ds.Tables[0];

        FileStream file = new FileStream(MapPath("~/OfficeTemplates/" + mathod + ".xls"), FileMode.Open, FileAccess.Read);//读入excel模板
        HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
        HSSFSheet sheet1 =(HSSFSheet) hssfworkbook.GetSheet("Sheet1");
        sheet1.GetRow(0).GetCell(0).SetCellValue(excelTitle);      //设置表头
        foreach (DataRow row in table.Rows)
        {   //双循环写入table中的数据
            rowIndex++;
            colIndex = 0;
            Row xlsrow = sheet1.CreateRow(rowIndex);
            foreach (DataColumn col in table.Columns)
            {
                xlsrow.CreateCell(colIndex).SetCellValue(row[col.ColumnName].ToString());
                colIndex++;
            }
        }

        sheet1.ForceFormulaRecalculation = true;
        FileStream fileS = new FileStream(MapPath("~/OfficeOutput/" + mathod + ".xls"), FileMode.Create);//保存
        hssfworkbook.Write(fileS);  
        fileS.Close();
        file.Close();

相关文章: