/// <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(); }