使用 NPOI/DocX 二次封装Office(Word、Excel)帮助类
简介
工作中需要大量生成导出报表或合同证书文件,原理为使用Excel或Word模板,批量替换标签以达到效果。
设计
由于原类库都属于基础方法,二次封装后具有更简易的使用方式,可直接传入生成的数据集或标签替换集合。
引用库介绍
由于微软默认推荐的类库 Microsoft.Office.Interop.Word 与 Microsoft.Office.Interop.Excel 需要电脑安装 Microsoft Office 并引用COM组件才可以使用(已知调用打印机需引用COM组件),所以选用类库可独立于Office组件,在任意一台电脑也可以运行。
NPOI:POI Java项目的.NET版本。可以非常轻松地读/写Office 2003/2007文件。
DocX:DocX是一个.NET库,允许开发人员以简单直观的方式操作Word文件。
Excel文件操作
ExcelHelper提供创建文件(2003/2007)及Sheet分页创建编辑,读取Excel文件至内存DataSet及反向DataSet保存至Excel文件。仅显示最外层引用方法,详细调用请在帮助类种查看!
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 
 | 
 
 
 
 public static DataSet ExcelConversionDataSet(string strDataSourcePath)
 {
 try
 {
 if (string.IsNullOrEmpty(strDataSourcePath) || !File.Exists(strDataSourcePath))
 {
 return null;
 }
 DataSet dsTargetData = new DataSet();
 Dictionary<int, string> dicAllSheet = GetExcelAllSheet(strDataSourcePath);
 foreach (var vAllSheet in dicAllSheet)
 {
 DataTable dtTargetData = new DataTable();
 dtTargetData.TableName = vAllSheet.Value;
 dtTargetData = ExcelConversionDataTable(strDataSourcePath, vAllSheet.Value);
 if (dtTargetData == null)
 {
 continue;
 }
 dsTargetData.Tables.Add(dtTargetData);
 }
 return dsTargetData;
 }
 catch (Exception ex)
 {
 TXTHelper.Logs(ex.ToString());
 return null;
 }
 }
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 
 | 
 
 
 
 
 
 
 public static bool DataSetConversionExcel(string strDataSourcePath, DataSet dsSourceData)
 {
 try
 {
 if (string.IsNullOrEmpty(strDataSourcePath) || dsSourceData.Tables.Count < 1)
 {
 return false;
 }
 foreach (DataTable dtSourceData in dsSourceData.Tables)
 {
 Dictionary<int, string> dicAllSheet = GetExcelAllSheet(strDataSourcePath);
 string strTableName = string.IsNullOrEmpty(dtSourceData.TableName) ? string.Format("Sheet{0}", dicAllSheet.Count + 1) : dtSourceData.TableName;
 if (dicAllSheet.ContainsValue(dtSourceData.TableName))
 {
 RemoveExcelSheet(strDataSourcePath, dtSourceData.TableName);
 }
 if (!FillDataTable(strDataSourcePath, strTableName, dtSourceData, true, 0, 0))
 {
 return false;
 }
 }
 return true;
 }
 catch (Exception ex)
 {
 TXTHelper.Logs(ex.ToString());
 return false;
 }
 }
 
 | 
根据公司项目需要,把多个Excel的Sheet页的内容及样式合并为一个文件,Microsoft.Office.Interop.Excel提供拷贝分页方法,但是需要安装Microsoft Office,所以用NPOI类库实现了一个拷贝方法。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 
 | 
 
 
 
 
 
 
 public static bool CopySheet(string strSourceExcelPath, string strFromSheetName, string strTargetExcelPath, string strToSheetName)
 {
 try
 {
 if (string.IsNullOrEmpty(strSourceExcelPath) || string.IsNullOrEmpty(strTargetExcelPath) || !File.Exists(strSourceExcelPath))
 {
 TXTHelper.Logs(string.Format("源数据和目标数据参数为空或文件不存在!"));
 return false;
 }
 if (string.IsNullOrEmpty(strFromSheetName) || string.IsNullOrEmpty(strToSheetName))
 {
 TXTHelper.Logs(string.Format("源Sheet页和目标Sheet页参数为空!"));
 return false;
 }
 
 IWorkbook iSourceWorkbook = null;
 ISheet iSourceSheet = GetExcelSheetAt(strSourceExcelPath, strFromSheetName, out iSourceWorkbook);
 IWorkbook iTargetWorkbook = null;
 ISheet iTargetSheet = null;
 if (iSourceSheet == null)
 {
 TXTHelper.Logs(string.Format("指定源数据Sheet页为空!"));
 return false;
 }
 if (!File.Exists(strTargetExcelPath))
 {
 
 if (System.IO.Path.GetExtension(strTargetExcelPath) == ".xls")
 {
 bool bCreare = CreateExcel_Office2003(strTargetExcelPath, strToSheetName);
 }
 else if (System.IO.Path.GetExtension(strTargetExcelPath) == ".xlsx")
 {
 bool bCreare = CreateExcel_Office2007(strTargetExcelPath, strToSheetName);
 }
 else
 {
 TXTHelper.Logs(string.Format("指定目标Excel文件路径格式错误!"));
 return false;
 }
 iTargetSheet = GetExcelSheetAt(strTargetExcelPath, strToSheetName, out iTargetWorkbook);
 }
 else
 {
 
 Dictionary<int, string> dicAllSheet = GetExcelAllSheet(strTargetExcelPath);
 if (dicAllSheet.ContainsValue(strToSheetName))
 {
 iTargetSheet = GetExcelSheetAt(strTargetExcelPath, strToSheetName, out iTargetWorkbook);
 }
 else
 {
 iTargetSheet = CreateExcelSheetAt(strTargetExcelPath, strToSheetName, out iTargetWorkbook);
 }
 }
 
 bool bCopySheet = CopySheetAt(iSourceWorkbook, iSourceSheet, iTargetWorkbook, iTargetSheet);
 if (bCopySheet)
 {
 if (System.IO.Path.GetExtension(strTargetExcelPath) == ".xls")
 {
 FileStream fileStream2003 = new FileStream(Path.ChangeExtension(strTargetExcelPath, "xls"), FileMode.Create);
 iTargetWorkbook.Write(fileStream2003);
 fileStream2003.Close();
 iTargetWorkbook.Close();
 }
 else if (System.IO.Path.GetExtension(strTargetExcelPath) == ".xlsx")
 {
 FileStream fileStream2007 = new FileStream(Path.ChangeExtension(strTargetExcelPath, "xlsx"), FileMode.Create);
 iTargetWorkbook.Write(fileStream2007);
 fileStream2007.Close();
 iTargetWorkbook.Close();
 }
 return true;
 }
 else
 {
 TXTHelper.Logs(string.Format("拷贝失败!"));
 return false;
 }
 }
 catch (Exception ex)
 {
 TXTHelper.Logs(ex.ToString());
 return false;
 }
 }
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 
 | 
 
 
 
 
 
 
 
 public static bool CopySheetAt(IWorkbook iSourceWorkbook, ISheet iFromSheet, IWorkbook iTargetWorkbook, ISheet iToSheet)
 {
 try
 {
 
 DataTable dtExcelFromData = GetDataTable(iFromSheet, false, 0, 0, 0, 0);
 iToSheet = FillDataTable(iToSheet, dtExcelFromData, false, 0, 0);
 
 for (int iMergedRegions = 0; iMergedRegions < iFromSheet.NumMergedRegions; iMergedRegions++)
 {
 iToSheet.AddMergedRegion(iFromSheet.GetMergedRegion(iMergedRegions));
 }
 
 List<ICellStyle> listCellStyle = new List<ICellStyle>();
 for (int iRowNum = 0; iRowNum <= iFromSheet.LastRowNum; iRowNum++)
 {
 IRow iFromRowData = iFromSheet.GetRow(iRowNum);
 IRow iToRowData = iToSheet.GetRow(iRowNum);
 if (iFromRowData == null || iToRowData == null)
 {
 continue;
 }
 
 short sFromHeight = iFromRowData.Height;
 iToRowData.Height = sFromHeight;
 
 for (int iRowCell = 0; iRowCell <= iFromRowData.LastCellNum; iRowCell++)
 {
 
 int iFromColumnWidth = iFromSheet.GetColumnWidth(iRowNum) / 256;
 iToSheet.SetColumnWidth(iRowNum, iFromColumnWidth * 256);
 
 ICell iFromCell = iFromRowData.GetCell(iRowCell);
 if (iFromCell != null)
 {
 
 ICellStyle iFromCellStyle = iFromCell.CellStyle;
 
 ICell iToCell = iToRowData.GetCell(iRowCell);
 if (iToCell == null) continue;
 #region 复制单元格样式
 
 ICellStyle iToNewCellStyle = null;
 foreach (ICellStyle vCellStyle in listCellStyle)
 {
 IFont iVToFont = vCellStyle.GetFont(iTargetWorkbook);
 IFont iFromFont = iFromCellStyle.GetFont(iSourceWorkbook);
 if (vCellStyle.Alignment == iFromCellStyle.Alignment &&
 vCellStyle.BorderBottom == iFromCellStyle.BorderBottom &&
 vCellStyle.BorderLeft == iFromCellStyle.BorderLeft &&
 vCellStyle.BorderRight == iFromCellStyle.BorderRight &&
 vCellStyle.BorderTop == iFromCellStyle.BorderTop &&
 vCellStyle.BottomBorderColor == iFromCellStyle.BottomBorderColor &&
 vCellStyle.DataFormat == iFromCellStyle.DataFormat &&
 vCellStyle.FillBackgroundColor == iFromCellStyle.FillBackgroundColor &&
 vCellStyle.FillForegroundColor == iFromCellStyle.FillForegroundColor &&
 vCellStyle.FillPattern == iFromCellStyle.FillPattern &&
 vCellStyle.Indention == iFromCellStyle.Indention &&
 vCellStyle.IsHidden == iFromCellStyle.IsHidden &&
 vCellStyle.IsLocked == iFromCellStyle.IsLocked &&
 vCellStyle.LeftBorderColor == iFromCellStyle.LeftBorderColor &&
 vCellStyle.RightBorderColor == iFromCellStyle.RightBorderColor &&
 vCellStyle.Rotation == iFromCellStyle.Rotation &&
 vCellStyle.TopBorderColor == iFromCellStyle.TopBorderColor &&
 vCellStyle.VerticalAlignment == iFromCellStyle.VerticalAlignment &&
 vCellStyle.WrapText == iFromCellStyle.WrapText &&
 
 iVToFont.Color == iFromFont.Color &&
 iVToFont.FontHeightInPoints == iFromFont.FontHeightInPoints &&
 iVToFont.FontName == iFromFont.FontName &&
 iVToFont.IsBold == iFromFont.IsBold &&
 iVToFont.IsItalic == iFromFont.IsItalic &&
 iVToFont.IsStrikeout == iFromFont.IsStrikeout &&
 iVToFont.Underline == iFromFont.Underline)
 {
 iToNewCellStyle = vCellStyle;
 break;
 }
 }
 if (iToNewCellStyle == null)
 {
 
 iToNewCellStyle = iTargetWorkbook.CreateCellStyle();
 
 iToNewCellStyle.Alignment = iFromCellStyle.Alignment;
 iToNewCellStyle.BorderBottom = iFromCellStyle.BorderBottom;
 iToNewCellStyle.BorderLeft = iFromCellStyle.BorderLeft;
 iToNewCellStyle.BorderRight = iFromCellStyle.BorderRight;
 iToNewCellStyle.BorderTop = iFromCellStyle.BorderTop;
 iToNewCellStyle.BottomBorderColor = iFromCellStyle.BottomBorderColor;
 iToNewCellStyle.DataFormat = iFromCellStyle.DataFormat;
 iToNewCellStyle.FillBackgroundColor = iFromCellStyle.FillBackgroundColor;
 iToNewCellStyle.FillForegroundColor = iFromCellStyle.FillForegroundColor;
 iToNewCellStyle.FillPattern = iFromCellStyle.FillPattern;
 iToNewCellStyle.Indention = iFromCellStyle.Indention;
 iToNewCellStyle.IsHidden = iFromCellStyle.IsHidden;
 iToNewCellStyle.IsLocked = iFromCellStyle.IsLocked;
 iToNewCellStyle.LeftBorderColor = iFromCellStyle.LeftBorderColor;
 iToNewCellStyle.RightBorderColor = iFromCellStyle.RightBorderColor;
 iToNewCellStyle.Rotation = iFromCellStyle.Rotation;
 iToNewCellStyle.TopBorderColor = iFromCellStyle.TopBorderColor;
 iToNewCellStyle.VerticalAlignment = iFromCellStyle.VerticalAlignment;
 iToNewCellStyle.WrapText = iFromCellStyle.WrapText;
 
 IFont iFromFont = iFromCellStyle.GetFont(iSourceWorkbook);
 IFont iToFont = iTargetWorkbook.CreateFont();
 iToFont.Color = iFromFont.Color;
 iToFont.FontHeightInPoints = iFromFont.FontHeightInPoints;
 iToFont.FontName = iFromFont.FontName;
 iToFont.IsBold = iFromFont.IsBold;
 iToFont.IsItalic = iFromFont.IsItalic;
 iToFont.IsStrikeout = iFromFont.IsStrikeout;
 iToFont.Underline = iFromFont.Underline;
 iToNewCellStyle.SetFont(iToFont);
 
 listCellStyle.Add(iToNewCellStyle);
 }
 
 iToCell.CellStyle = iToNewCellStyle;
 #endregion
 }
 }
 }
 return true;
 }
 catch (Exception ex)
 {
 TXTHelper.Logs(ex.ToString());
 return false;
 }
 }
 
 | 
Word文件操作
WordHelper提供创建文件(2003/2007)及替换段落表格标签(匹配替换’{标签}’,’#标签#’),替换图片功能。仅显示最外层引用方法,详细调用请在帮助类种查看!
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 
 | 
 
 
 
 
 
 public static int ReplaceTextLabel(string strDataSourcePath, string strLabelName, string strReplaceLabel)
 {
 try
 {
 if (string.IsNullOrEmpty(strDataSourcePath) || !File.Exists(strDataSourcePath) || string.IsNullOrEmpty(strLabelName) || string.IsNullOrEmpty(strReplaceLabel))
 {
 return -1;
 }
 int iNumber = 0;
 FileStream fileStreamOpen = new FileStream(strDataSourcePath, FileMode.Open, FileAccess.Read);
 XWPFDocument wordDocument = new XWPFDocument(fileStreamOpen);
 foreach (XWPFParagraph wordParagraph in wordDocument.Paragraphs)
 {
 if (wordParagraph.ParagraphText.IndexOf(strLabelName) >= 0)
 {
 string strReplaceTextLabel = wordParagraph.ParagraphText.Replace(strLabelName, strReplaceLabel);
 foreach (XWPFRun wordRun in wordParagraph.Runs)
 {
 wordRun.SetText(string.Empty, 0);
 }
 wordParagraph.CreateRun().SetText(strReplaceTextLabel, 0);
 iNumber++;
 }
 }
 foreach (XWPFTable wordTable in wordDocument.Tables)
 {
 foreach (XWPFTableRow wordTableRow in wordTable.Rows)
 {
 foreach (XWPFTableCell wordTableCell in wordTableRow.GetTableCells())
 {
 foreach (XWPFParagraph wordParagraph in wordTableCell.Paragraphs)
 {
 if (wordParagraph.ParagraphText.IndexOf(strLabelName) >= 0)
 {
 string strReplaceTextLabel = wordParagraph.ParagraphText.Replace(strLabelName, strReplaceLabel);
 foreach (XWPFRun wordRun in wordParagraph.Runs)
 {
 wordRun.SetText(string.Empty, 0);
 }
 wordParagraph.CreateRun().SetText(strReplaceTextLabel, 0);
 iNumber++;
 }
 }
 }
 }
 }
 FileStream fileStreamSave = new FileStream(strDataSourcePath, FileMode.Create);
 wordDocument.Write(fileStreamSave);
 fileStreamSave.Close();
 wordDocument.Close();
 return iNumber;
 }
 catch (Exception ex)
 {
 TXTHelper.Logs(ex.ToString());
 return -1;
 }
 }
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 
 | 
 
 
 
 
 
 public static int ReplaceDataTableLabel(string strDataSourcePath, string strLabelName, DataTable dtReplaceLabel)
 {
 try
 {
 if (string.IsNullOrEmpty(strDataSourcePath) || !File.Exists(strDataSourcePath) || string.IsNullOrEmpty(strLabelName) || dtReplaceLabel == null || dtReplaceLabel.Rows.Count < 1)
 {
 return -1;
 }
 FileStream fileStreamOpen = new FileStream(strDataSourcePath, FileMode.Open, FileAccess.Read);
 XWPFDocument wordDocument = new XWPFDocument(fileStreamOpen);
 int iLableRowPosition = -1;
 int iLableCellPosition = -1;
 foreach (XWPFTable wordTable in wordDocument.Tables)
 {
 for (int iTableRow = 0; iTableRow < wordTable.Rows.Count; iTableRow++)
 {
 for (int iTableCell = 0; iTableCell < wordTable.Rows[iTableRow].GetTableCells().Count; iTableCell++)
 {
 foreach (XWPFParagraph wordParagraph in wordTable.Rows[iTableRow].GetTableCells()[iTableCell].Paragraphs)
 {
 if (wordParagraph.ParagraphText.IndexOf(strLabelName) >= 0)
 {
 if (iLableRowPosition < 0 && iLableCellPosition < 0)
 {
 iLableRowPosition = iTableRow;
 iLableCellPosition = iTableCell;
 }
 }
 if (iLableRowPosition >= 0 && iLableCellPosition >= 0)
 {
 int iCurrentRow = iTableRow - iLableRowPosition;
 int iCurrentCell = iTableCell - iLableCellPosition;
 if ((iCurrentRow < dtReplaceLabel.Rows.Count && iCurrentRow >= 0) && (iCurrentCell < dtReplaceLabel.Columns.Count && iCurrentCell >= 0))
 {
 foreach (XWPFRun wordRun in wordParagraph.Runs)
 {
 wordRun.SetText(string.Empty, 0);
 }
 wordParagraph.CreateRun().SetText(dtReplaceLabel.Rows[iCurrentRow][iCurrentCell].ToString(), 0);
 }
 }
 }
 }
 }
 }
 FileStream fileStreamSave = new FileStream(strDataSourcePath, FileMode.Create);
 wordDocument.Write(fileStreamSave);
 fileStreamSave.Close();
 wordDocument.Close();
 return 1;
 }
 catch (Exception ex)
 {
 TXTHelper.Logs(ex.ToString());
 return -1;
 }
 }
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 
 | 
 
 
 
 
 
 
 
 public static int ReplaceImageLabel(string strDataSourcePath, string strLabelName, string strImagePath, int iImageWidth, int iImageHeight)
 {
 try
 {
 if (string.IsNullOrEmpty(strDataSourcePath) || !File.Exists(strDataSourcePath) || string.IsNullOrEmpty(strLabelName) || string.IsNullOrEmpty(strImagePath) || !File.Exists(strImagePath))
 {
 return -1;
 }
 int iNumber = 0;
 
 DocX mDocX = DocX.Load(strDataSourcePath);
 
 foreach (Paragraph wordParagraph in mDocX.Paragraphs)
 {
 if (wordParagraph.Text.IndexOf(strLabelName) >= 0)
 {
 
 Novacode.Image pImag = mDocX.AddImage(strImagePath);
 Picture pPicture = pImag.CreatePicture();
 
 if (iImageWidth >= 0)
 {
 pPicture.Width = iImageWidth;
 }
 
 if (iImageHeight >= 0)
 {
 pPicture.Height = iImageHeight;
 }
 
 wordParagraph.InsertPicture(pPicture);
 
 wordParagraph.ReplaceText(strLabelName, string.Empty);
 iNumber++;
 }
 }
 mDocX.SaveAs(strDataSourcePath);
 return iNumber;
 }
 catch (Exception ex)
 {
 TXTHelper.Logs(ex.ToString());
 return -1;
 }
 }
 
 |