第一次做这个写入数据的功能,研究了下npoi的类
IWorkbook wb = new HSSFWorkbook(); //创建表 ISheet sh = wb.CreateSheet("XXX"); //设置单元的宽度 sh.SetColumnWidth(0, 20 * 256); #region 合并单元格 IRow row0 = sh.CreateRow(0); row0.Height = 20 * 20; ICell icell1top0 = row0.CreateCell(0); icell1top0.CellStyle = Getcellstyle(wb, stylexls.头); icell1top0.SetCellValue(getTitle()); #endregion #region 创建问题题目 IRow row1 = sh.CreateRow(1); // row1.Height = 20 * 20; ICell icell = null; ICell icell1top = row1.CreateCell(0); icell1top.CellStyle = Getcellstyle(wb, stylexls.头); icell1top.SetCellValue("姓名/问卷题目"); string sqlAll = "select * from dbo.CheckMgr where UserID=" + rqid + " order by T_Sort asc"; DataTable dtAll = SystemDAL.SQLHelper.GetTable(sqlAll); if (dtAll != null && dtAll.Rows.Count > 0) { for (int j = 0; j < dtAll.Rows.Count; j++) { sh.SetColumnWidth(j + 1, 40 * 256); //合并单元格//表头
//CellRangeAddress()该方法的参数次序是:开始行号,结束行号,开始列号,结束列号。 sh.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtAll.Rows.Count)); string title = dtAll.Rows[j]["T_title"].ToString(); icell = row1.CreateCell(j + 1); icell.SetCellValue(title); } } #endregion #region 创建对应题目的答案内容 DataTable dtUser = getUserInfo(); IRow row11 = null; for (int a = 0; a < dtUser.Rows.Count; a++)//学生 { row11 = sh.CreateRow(a + 2); string user = dtUser.Rows[a]["realname"].ToString(); string id = dtUser.Rows[a]["id"].ToString(); for (int b = 0; b < dtAll.Rows.Count; b++)//题目 { //每一行的第一列//用户姓名 HSSFCell cell11 = row11.CreateCell(0) as HSSFCell; cell11.SetCellValue(user); DataTable dtInfo = getAnwer(id); if (dtInfo != null && dtInfo.Rows.Count > 0) { for (int i = 0; i < dtInfo.Rows.Count; i++) { string key = dtInfo.Rows[b]["Ckey"].ToString(); string value = dtInfo.Rows[b]["Cvalue"].ToString(); string title = getMgrTitle(key, value); HSSFCell cell1 = row11.CreateCell(b + 1) as HSSFCell; cell1.SetCellValue(title); } } } } #endregion #region 下载Excel Random r = new Random(); string _fileName = string.Format("{0:yyyyMMddHHmmssfff}-{1}", DateTime.Now, r.Next(1, 9999)) + ".xls"; using (MemoryStream ms = new MemoryStream()) { wb.Write(ms); Response.Clear(); Response.ClearHeaders(); Response.Buffer = false; Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.ASCII)); Response.AppendHeader("Content-Length", ms.Length.ToString()); Response.BinaryWrite(ms.GetBuffer()); Response.Flush(); Response.End(); } #endregion
效果: