protected string ExportZ(DataSet ds, string filename) { MemoryStream ms = null; try { ms = new MemoryStream(); IWorkbook xssfworkbook = null; if (filename.IndexOf(".xlsx") > -1) { xssfworkbook = new XSSFWorkbook(); } else xssfworkbook = new HSSFWorkbook(); ISheet sheet = xssfworkbook.CreateSheet("sheet1"); sheet.SetColumnWidth(0, 20 * 256); sheet.SetColumnWidth(1, 30 * 256); sheet.SetColumnWidth(2, 20 * 256); sheet.SetColumnWidth(3, 20 * 256); sheet.SetColumnWidth(4, 20 * 256); IRow irow = sheet.CreateRow(0); irow.CreateCell(0).SetCellValue("單位名稱"); irow.CreateCell(1).SetCellValue("入駐時項目名稱"); irow.CreateCell(2).SetCellValue("企業注冊時間"); irow.CreateCell(3).SetCellValue("聯系人"); irow.CreateCell(4).SetCellValue("聯系方式"); int i = 1; foreach (DataRow row in ds.Tables[0].Rows) { sheet.CreateRow(i).CreateCell(0).SetCellValue(row["Company"] + ""); sheet.GetRow(i).CreateCell(1).SetCellValue(row["ProjectName"] + ""); sheet.GetRow(i).CreateCell(2).SetCellValue(Convert.ToDateTime(row["RegisteredDate"] + "").ToString("yyyy-MM-dd HH:mm:ss")); sheet.GetRow(i).CreateCell(3).SetCellValue(row["Contact"] + ""); sheet.GetRow(i).CreateCell(4).SetCellValue(row["MobilePhone"] + ""); i++; } string pathstr = System.Web.HttpContext.Current.Server.MapPath(Public.Path_Inspection); if (!System.IO.Directory.Exists(pathstr)) System.IO.Directory.CreateDirectory(pathstr); xssfworkbook.Write(ms); string filePath = System.Web.HttpContext.Current.Server.MapPath(Public.Path_Inspection + "/" + filename); FileStream file = new FileStream(filePath, FileMode.Create); xssfworkbook.Write(file); file.Close(); return Public.Path_Inspection + "/" + filename; } catch (Exception ex) { throw ex; } finally { ms.Dispose(); } }
/// <summary> /// 合並單元格 /// </summary> /// <param name="sheet">要合並單元格所在的sheet</param> /// <param name="rowstart">開始行的索引</param> /// <param name="rowend">結束行的索引</param> /// <param name="colstart">開始列的索引</param> /// <param name="colend">結束列的索引</param> public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend) { CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend); sheet.AddMergedRegion(cellRangeAddress); }