使用第三方组件NPOI和iTextSharp根据DataTable导出Excel、Word、Pdf

广昊昊
2023-12-01
源码及组件下载地址: 源码及NPOI 2.0和itextsharp-all-5.5.3
源码如下:

using System; using System.Collections.Generic; using System.Data; using System.Text; using NPOI; using NPOI.HPSF; using NPOI.HSSF; using NPOI.HSSF.UserModel; using NPOI.HSSF.Util; using NPOI.POIFS; using NPOI.Util; using System.IO; using NPOI.XWPF.UserModel; using NPOI.XSSF.UserModel; using iTextSharp; using iTextSharp.text; using iTextSharp.text.pdf; namespace MyUtil { public static class ExportData { /// <summary> /// 导出Pdf /// </summary> /// <param name="path">文件保存路径</param> /// <param name="dtSource">数据源</param> /// <param name="HorV">页面横竖(为空表示竖,有非空值为横)</param> public static void ExportPDF(string localFilePath, DataTable dtSource, string HorV) { iTextSharp.text.io.StreamUtil.AddToResourceSearch("iTextAsian.dll"); iTextSharp.text.io.StreamUtil.AddToResourceSearch("iTextAsianCmaps.dll"); BaseFont bf; string basepath = Application.StartupPath; try { bf = BaseFont.CreateFont(basepath + "\\FONTS\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); } catch { bf = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); } iTextSharp.text.Font font = new iTextSharp.text.Font(bf); iTextSharp.text.Document pdf; if (string.IsNullOrEmpty(HorV)) pdf = new iTextSharp.text.Document(); else pdf = new iTextSharp.text.Document(PageSize.A4.Rotate()); PdfPTable table = new PdfPTable(dtSource.Columns.Count); table.HorizontalAlignment = Element.ALIGN_CENTER; PdfPCell cell; for (int i = 0; i < dtSource.Rows.Count + 1; i++) { for (int j = 0; j < dtSource.Columns.Count; j++) { if (i == 0) { cell = new PdfPCell(new Phrase(dtSource.Columns[j].ColumnName, font)); } else { cell = new PdfPCell(new Phrase(dtSource.Rows[i - 1][j].ToString(), font)); } table.AddCell(cell); } } using (FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write)) { PdfWriter.GetInstance(pdf, fs); pdf.Open(); pdf.Add(table); pdf.Close(); } } /// <summary> /// 导出Xls /// </summary> /// <param name="localFilePath">文件保存路径</param> /// <param name="dtSource">数据源</param> public static void ExportXls(string localFilePath, DataTable dtSource) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(); HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle(); HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); //取得列宽 int[] arrColWidth = new int[dtSource.Columns.Count]; 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 < dtSource.Columns.Count; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } } int rowIndex = 0; foreach (DataRow row in dtSource.Rows) { #region 新建Sheet,填充列头,样式 if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = (HSSFSheet)workbook.CreateSheet(); } #region 列头及样式 { HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0); HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; HSSFFont font = (HSSFFont)workbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headStyle.SetFont(font); 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 填充内容 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); foreach (DataColumn column in dtSource.Columns) { HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Ordinal); string drValue = row[column].ToString(); switch (column.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 (FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write)) { workbook.Write(fs); } } /// <summary> /// 导出Xlsx /// </summary> /// <param name="localFilePath">文件保存路径</param> /// <param name="dtSource">数据源</param> public static void ExportXlsx(string localFilePath, DataTable dtSource) { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet(); XSSFCellStyle dateStyle = (XSSFCellStyle)workbook.CreateCellStyle(); XSSFDataFormat format = (XSSFDataFormat)workbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); //取得列宽 int[] arrColWidth = new int[dtSource.Columns.Count]; 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 < dtSource.Columns.Count; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } } int rowIndex = 0; foreach (DataRow row in dtSource.Rows) { #region 新建表,填充列头,样式 if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = (XSSFSheet)workbook.CreateSheet(); } #region 列头及样式 { XSSFRow headerRow = (XSSFRow)sheet.CreateRow(0); XSSFCellStyle headStyle = (XSSFCellStyle)workbook.CreateCellStyle(); headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; XSSFFont font = (XSSFFont)workbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headStyle.SetFont(font); 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 填充内容 XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex); foreach (DataColumn column in dtSource.Columns) { XSSFCell newCell = (XSSFCell)dataRow.CreateCell(column.Ordinal); string drValue = row[column].ToString(); switch (column.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 (FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write)) { workbook.Write(fs); } } /// <summary> /// 导出Docx /// </summary> /// <param name="localFilePath">文件保存路径</param> /// <param name="dtSource">数据源</param> public static void ExportDocx(string localFilePath, DataTable dtSource) { XWPFDocument doc = new XWPFDocument(); XWPFTable table = doc.CreateTable(dtSource.Rows.Count + 1, dtSource.Columns.Count); for (int i = 0; i < dtSource.Rows.Count + 1; i++) { for (int j = 0; j < dtSource.Columns.Count; j++) { if (i == 0) { table.GetRow(i).GetCell(j).SetText(dtSource.Columns[j].ColumnName); } else { table.GetRow(i).GetCell(j).SetText(dtSource.Rows[i - 1][j].ToString()); } } } using (FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write)) { doc.Write(fs); } } } }


 类似资料: