DataTable导出到Excel文件
调用方法: ExcelHelper.Export(dtTemp, "供应商App", DlgSave.FileName, "物料文档" , new string[10] { "MatterCode", "MatterName", "MatterType", "MainUnit", "TagModelName", "LotName", "FMatterCode", "FMatterName", "FMatterType", "TagNumber" } , new string[10] { "MatterCode", "MatterName", "MatterType", "MainUnit", "TagModelName", "LotName", "FMatterCode", "FMatterName", "FMatterType", "TagNumber" });
/// <summary> /// DataTable导出到Excel文件 /// </summary> /// <param name="dtSource">源DataTable</param> /// <param name="strHeaderText">表头文本</param> /// <param name="strFileName">保存位置</param> /// <param name="strSheetName">工作表名称</param> public static void Export(DataTable dtSource, string strHeaderText, string strFileName, string strSheetName, string[] oldColumnNames, string[] newColumnNames) { if (strSheetName == "") { strSheetName = "Sheet"; } using (MemoryStream ms = Export(dtSource, strHeaderText, strSheetName, oldColumnNames, newColumnNames)) { using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } } } /// <summary> /// DataTable导出到Excel的MemoryStream /// </summary> /// <param name="dtSource">源DataTable</param> /// <param name="strHeaderText">表头文本</param> /// <param name="strSheetName">工作表名称</param> public static MemoryStream Export(DataTable dtSource, string strHeaderText, string strSheetName, string[] oldColumnNames, string[] newColumnNames) { if (oldColumnNames.Length != newColumnNames.Length) { return new MemoryStream(); } HSSFWorkbook workbook = new HSSFWorkbook(); //HSSFSheet sheet = workbook.CreateSheet();// workbook.CreateSheet(); ISheet sheet = workbook.CreateSheet(strSheetName); #region 右击文件 属性信息 { DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = ""; workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); //填加xls文件作者信息 si.Author = ""; si.ApplicationName = ""; //填加xls文件创建程序信息 si.LastAuthor = ""; //填加xls文件最后保存者信息 si.Comments = ""; //填加xls文件作者信息 si.Title = strHeaderText; //填加xls文件标题信息 si.Subject = strHeaderText; //填加文件主题信息 si.CreateDateTime = DateTime.Now; workbook.SummaryInformation = si; } #endregion ICellStyle dateStyle = workbook.CreateCellStyle(); IDataFormat format = workbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); #region 取得列宽 int[] arrColWidth = new int[oldColumnNames.Length]; for (int i = 0; i < oldColumnNames.Length; i++) { arrColWidth[i] = Encoding.GetEncoding(936).GetBytes(newColumnNames[i]).Length; } /* foreach (DataColumn item in dtSource.Columns) { arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; } * */ for (int i = 0; i < dtSource.Rows.Count; i++) { for (int j = 0; j < oldColumnNames.Length; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][oldColumnNames[j]].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } /* for (int j = 0; j < dtSource.Columns.Count; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } * */ } #endregion int rowIndex = 0; foreach (DataRow row in dtSource.Rows) { #region 新建表,填充表头,填充列头,样式 if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = workbook.CreateSheet(strSheetName + ((int)rowIndex / 65535).ToString()); } #region 表头及样式 //{ // IRow headerRow = sheet.CreateRow(0); // headerRow.HeightInPoints = 25; // headerRow.CreateCell(0).SetCellValue(strHeaderText); // ICellStyle headStyle = workbook.CreateCellStyle(); // headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER; // IFont font = workbook.CreateFont(); // font.FontHeightInPoints = 20; // font.Boldweight = 700; // headStyle.SetFont(font); // headerRow.GetCell(0).CellStyle = headStyle; // //sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); // sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, oldColumnNames.Length - 1)); //} #endregion #region 列头及样式 { //HSSFRow headerRow = sheet.CreateRow(1); IRow headerRow = sheet.CreateRow(0); ICellStyle headStyle = workbook.CreateCellStyle(); headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER; IFont font = workbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headStyle.SetFont(font); for (int i = 0; i < oldColumnNames.Length; i++) { headerRow.CreateCell(i).SetCellValue(newColumnNames[i]); headerRow.GetCell(i).CellStyle = headStyle; //设置列宽 sheet.SetColumnWidth(i, (arrColWidth[i] + 1) * 256); } /* foreach (DataColumn column in dtSource.Columns) { headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); headerRow.GetCell(column.Ordinal).CellStyle = headStyle; //设置列宽 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); } * */ } #endregion rowIndex = 1; } #endregion #region 填充内容 IRow dataRow = sheet.CreateRow(rowIndex); //foreach (DataColumn column in dtSource.Columns) for (int i = 0; i < oldColumnNames.Length; i++) { ICell newCell = dataRow.CreateCell(i); string drValue = row[oldColumnNames[i]].ToString(); switch (dtSource.Columns[oldColumnNames[i]].DataType.ToString()) { case "System.String"://字符串类型 newCell.SetCellValue(drValue); break; case "System.DateTime"://日期类型 DateTime dateV; DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle;//格式化显示 break; case "System.Boolean"://布尔型 bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break; case "System.Int16"://整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break; case "System.Decimal"://浮点型 case "System.Double": double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break; case "System.DBNull"://空值处理 newCell.SetCellValue(""); break; default: newCell.SetCellValue(""); break; } } #endregion rowIndex++; } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; //sheet.Dispose(); sheet = null; workbook = null; //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet return ms; } }