用npoi生成excel的文章已经有很多,我这就不多说了,今天主要的目的就是把我写的例子贴出来和大家分享
如果有不明白的地方,可以联系我
public static string ExportExcel(DataTable dtSource, string AppSettingPath,string Aid) { try { string AdPath = string.Empty; string FileName = string.Empty; HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(); //填充表头 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0); foreach (DataColumn column in dtSource.Columns) { dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName == ""); } //填充内容 for (int i = 0; i < dtSource.Rows.Count; i++) { dataRow = (HSSFRow)sheet.CreateRow(i + 1); for (int j = 0; j < dtSource.Columns.Count; j++) { dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString()); } } //保存 using (MemoryStream ms = new MemoryStream()) { // FileName=DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls"; FileName = Aid + ".xls"; AdPath = System.Web.HttpContext.Current.Server.MapPath(AppSettingPath) + FileName; using (FileStream fs = new FileStream(AdPath, FileMode.Create, FileAccess.Write)) { workbook.Write(fs); } } workbook.Dispose(); if (FileName != string.Empty) { return CmsUrl + AppSettingPath + FileName; } else { return string.Empty; } } catch(Exception ex) { throw new Exception(ex.Message,ex); } }