/// <summary> /// 導入excel /// </summary> /// <param name="strFilePath"></param> /// <returns></returns> public static DataTable ImportCompareMeanExcel(string strFilePath) { Workbook workbook = new Workbook(); DataTable dtExcel = null; try { workbook.Open(strFilePath); Cells cells = workbook.Worksheets[0].Cells; dtExcel = cells.ExportDataTableAsString(12, 0, cells.MaxDataRow + 1, cells.MaxColumn + 1, true);//showTitle } catch (Exception ex) { throw new Exception(ex.Message); } return dtExcel; }
/// <summary> /// 根據excel模板導出數據 /// </summary> /// <param name="context"></param> /// <param name="model">數據</param> /// <param name="templateFileName">模板路徑</param> /// <param name="sheetName">excel工作簿名稱</param> /// <param name="fileNameHead">導出文件名稱</param> /// <param name="action">需要補充的數據</param> public static void DataTableExportIsExcel(HttpContext context, DataTable model, string templateFileName, string sheetName, string fileNameHead,Action<WorkbookDesigner, DataTable> action) { MemoryStream ms = ExportHelper.OutModelFileToStream(model, templateFileName, sheetName, action); byte[] bt = ms.ToArray(); string fileName = fileNameHead + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; //客戶端保存的文件名 //以字符流的形式下載文件 context.Response.ContentType = "application/vnd.ms-excel"; //通知瀏覽器下載文件而不是打開 context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); context.Response.BinaryWrite(bt); context.Response.Flush(); context.Response.End(); } /// <summary> /// 返回excel文件流 /// </summary> /// <param name="model">數據</param> /// <param name="templateFileName">模板路徑</param> /// <param name="sheetName">excel工作簿名稱</param> /// <param name="fileNameHead">導出文件名稱</param> /// <param name="action">需要補充的數據</param> /// <returns>excel文件流</returns> public static MemoryStream OutModelFileToStream(DataTable model, string templateFileName, string sheetName, Action<WorkbookDesigner, DataTable> action) { WorkbookDesigner designer = new WorkbookDesigner(); designer.Open(templateFileName); designer.SetDataSource(model); //對designer做額外操作 if (action != null) { action(designer, model); } designer.Process(); if (!string.IsNullOrEmpty(sheetName)) { designer.Workbook.Worksheets[0].Name = sheetName; } return designer.Workbook.SaveToStream(); }