.net NPOI匯出EXCEL多個sheet
阿新 • • 發佈:2018-11-29
protected void Button3_Click(object sender, EventArgs e) { DataTable dt = null; string tempprovince = ""; string sql = ""; List<StringBuilder> listtabler = new List<StringBuilder>(); string sql2 = "select province from hq_applytry group by province "; DataTable dt2 = DbHelp.GetDataTable(sql2); HSSFWorkbook book = new HSSFWorkbook(); System.IO.MemoryStream ms = new System.IO.MemoryStream(); if (dt2.Rows.Count > 0) { for (int i = 0; i < dt2.Rows.Count; i++) { tempprovince = dt2.Rows[i]["province"].ToString(); sql = "select t.* from hq_applytry t where province='" + tempprovince + "' "; dt = DbHelp.GetDataTable(sql); DataTable tempTable = dt; ICellStyle styleTitle = book.CreateCellStyle(); styleTitle.WrapText = true;//自動換行 //增加sheet HSSFSheet sheet = (HSSFSheet)book.CreateSheet(tempprovince);//Sheet名稱 sheet.SetColumnWidth(1, 20 * 256); sheet.SetColumnWidth(3, 15 * 256); sheet.SetColumnWidth(10, 30 * 256); HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0); //foreach (DataColumn column in tempTable.Columns) //{ // //建立列 // headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); //} headerRow.CreateCell(0).SetCellValue("ID"); headerRow.CreateCell(1).SetCellValue("公司名稱"); headerRow.CreateCell(2).SetCellValue("法人/聯絡人"); headerRow.CreateCell(3).SetCellValue("電話"); headerRow.CreateCell(4).SetCellValue("微訊號"); headerRow.CreateCell(5).SetCellValue("團隊人數"); headerRow.CreateCell(6).SetCellValue("省"); headerRow.CreateCell(7).SetCellValue("市/縣/區"); headerRow.CreateCell(8).SetCellValue("鄉/鎮/街道"); headerRow.CreateCell(9).SetCellValue("推薦人"); headerRow.CreateCell(10).SetCellValue("申請理由"); headerRow.CreateCell(11).SetCellValue("申請時間"); int rowIndex = 1; foreach (DataRow row in tempTable.Rows) { //建立行 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); foreach (DataColumn column in tempTable.Columns) { dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); } rowIndex++; } } book.Write(ms); byte[] strmByte = ms.ToArray(); ms.Dispose(); Response.ClearContent(); Response.ContentEncoding = System.Text.Encoding.UTF8; Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment;fileName=" + "加盟"+ DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"); Response.BinaryWrite(strmByte); } }