Word文档导出之NPOI (.Net core6.0)
.Net Word操作之NPOI
开发过程中参考文献:
(12条消息) NPOI导出Word并插入表格和图片_栖于山的博客-CSDN博客_npoi word 插入表格
(12条消息) C# 图片操作(图片读取,保存,转换,传输)_无熵~的博客-CSDN博客_c#图像传输
(12条消息) POI Word设置背景色(以不同颜色突出显示文本)和底纹_小百菜的博客-CSDN博客_poi word 底纹
一、使用.net core 控制台应用程序编写了一个测试程序
1、创建应用程序
2、控制台入口调用相关方法
3、右键新建一个类库-用于编写导出代码
4、利用Nuget获取NPOI并安装, 这里引用的2.6.0最稳定版本(类库安装)
5、简单使用
5.1、XWPFDocument类的实例化
该类的实例对应一个word文档
XWPFDocument MyDoc = new XWPFDocument();
5.2、设置页面的大小
如果不进行页面大小的设置,默认是纵向的A4大小。横向的A4的页面大小 ,如果要纵向,宽高两个值调换即可。
T_SectPr m_SectPr = new CT_SectPr(); //实例一个尺寸类的实例 m_SectPr.pgSz.w = 16838; //设置宽度(这里是一个ulong类型) m_SectPr.pgSz.h = 11906; //设置高度(这里是一个ulong类型) MyDoc.Document.body.sectPr = m_SectPr; //设置页面的尺寸
这里的单位比较特殊,用的是缇(Twip)这是一种和屏幕无关的长度单位,目的是为了让应用程序元素输出到不同设备时都能保持一致的计算方式。
换算关系:
- 1英寸=1440缇
- 1厘米=567缇
- 1磅=20缇
- 1像素=15缇
常用页面尺寸:(单位Twip)
- A4(纵向):W=11906 H=16838
- A4(横向):W=16838 H=11906
- A5 : W=8390 H=11906
- A6 : W=5953 H=8390
示例:控制word页内边距
//创建document对象 var doc = new XWPFDocument(); doc.Document.body.sectPr = new CT_SectPr(); CT_SectPr m_SectPr = doc.Document.body.sectPr;
//页面大小 m_SectPr.pgSz.h = (ulong)16838; m_SectPr.pgSz.w = (ulong)11906; //页面边距 m_SectPr.pgMar.left = (ulong)800;//左边距 m_SectPr.pgMar.right = (ulong)800;//右边距 m_SectPr.pgMar.top = (ulong)850;//上边距 m_SectPr.pgMar.bottom = (ulong)850;//下边距
doc.Document.body.sectPr = srcpr;
5.3、表格处理
doc.Tables 获取文档里的所有的表格对象;//doc.Tables获取的只是Word中最外层的表格,不包含嵌套内层的。
cell.Tables;//获取嵌套单元格可使用
row.Rows //获取表格所有行;
row.GetTableICells() ;//获取表格行的所有单元格;
获取到单元格之后就可以获取单元格里的文本段落(Paragraphs)并且进行文本替换
创建表格
var table = doc.CreateTable(行数, 列数); table.Width = 5000;
控制表格中列宽(这里需要注意,只设置一行的列宽一旦插入文字就会使设置的列宽失效,所以要把每一个单元格都要设置上)
C#NPOI设置WORD中表格TABLE的固定列宽 - 不存在的马飞飞 - 博客园 (cnblogs.com)
//固定宽
table.GetCTTbl().AddNewTblPr().tblLayout = new CT_TblLayoutType() { type = ST_TblLayoutType.@fixed };
//控制表格列宽
//页面放置内容宽度
var conwidth = srcpr.pgSz.w - srcpr.pgMar.left - srcpr.pgMar.right;
table.SetColumnWidth(0, conwidth / 2);
table.SetColumnWidth(1, conwidth / 2);
控制表格中行高
//页面放置内容高度
var conheight = srcpr.pgSz.h - srcpr.pgMar.top - srcpr.pgMar.bottom;
//行高 table.GetRow(0).GetCTRow().AddNewTrPr().AddNewTrHeight().val = conheight;
设置表格边框
using CT_Border = NPOI.OpenXmlFormats.Wordprocessing.CT_Border; using NPOI.OpenXmlFormats.Wordprocessing;
CT_TblBorders borders = table.GetTrPr().AddNewTblBorders(); CT_Border hBorder = borders.AddNewInsideH(); //内部行边框样式 CT_Border vBorder = borders.AddNewInsideV(); //内部列边框样式 CT_Border leftBorder = borders.AddNewLeft(); //左框线 CT_Border rightBorder = borders.AddNewRight();//右框线 CT_Border topBorder = borders.AddNewTop();//上框线 CT_Border bottomBorder = borders.AddNewBottom();//下框线 //table表格内部行边框 内部横框线 hBorder.val = ST_Border.dotted; hBorder.color = "green"; //table表格内部列边框 内部竖框线 vBorder.val = ST_Border.dotted; vBorder.color = "blue"; //左边框 leftBorder.val = ST_Border.dotted; leftBorder.color = "red"; //右边框 rightBorder.val = ST_Border.dotted; rightBorder.color = "red"; //上边框 topBorder.val = ST_Border.dotted; topBorder.color = "red"; //下边框 bottomBorder.val = ST_Border.dotted; bottomBorder.color = "red";
设置表格中单元格竖直居中(单元格内容垂直居中)
var rowcell = table.GetRow(r).GetCell(c); rowcell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
设置单元格内容
//table中的文字格式设置 var para = new CT_P();
//创建表格当中的段落对象 var pCell = new XWPFParagraph(para, table.Body); //是一个小段落 pCell.Alignment = paragraphAlignment; //字体居中 pCell.VerticalAlignment = TextAlignment.CENTER; //字体居中 var r1c1 = pCell.CreateRun(); r1c1.SetText(setText); r1c1.FontSize = 11; r1c1.SetFontFamily("宋体", FontCharRange.None); //设置宋体字体
//控制段落与其他元素的上下距离 pCell.SpacingAfterLines = 40;//下方距离 pCell.SpacingBeforeLines = 40;//上方距离
//设置文本高度(行间距)
pCell.TextPosition=120; //放入单元格 table.GetRow(4).GetCell(1).SetParagraph(pCell);
表格中换行
var run= paragraph.CreateRun(); run.SetText(contends[i]); run.FontSize = 11; run.SetFontFamily("宋体", FontCharRange.None); //字体 run.AddBreak(BreakType.TEXTWRAPPING);//换行
合并单元格
table.GetRow(rowIndex).MergeCells(fromCol, toCol);//合并列
水平合并行单元格
CT_Tc cttcofRowThird = cell.GetCTTc(); CT_TcPr ctProfRowThird = cttcofRowThird.AddNewTcPr(); ctProfRowThird.gridSpan = new CT_DecimalNumber(); ctProfRowThird.gridSpan.val = num.ToString();//合并num列
合并行、垂直合并列单元格
public void MYMergeRows(XWPFTable table, int fromRow, int toRow, int colIndex) { for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) { XWPFTableCell rowcell = table.GetRow(rowIndex).GetCell(colIndex); rowcell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); CT_Tc cttc = rowcell.GetCTTc(); CT_TcPr ctTcPr = cttc.tcPr; if (ctTcPr == null) { ctTcPr = cttc.AddNewTcPr(); } if (rowIndex == fromRow) { // The first merged cell is set with RESTART merge value ctTcPr.AddNewVMerge().val = ST_Merge.restart; } else { // Cells which join (merge) the first one, are set with CONTINUE ctTcPr.AddNewVMerge().val = ST_Merge.@continue;//继续合并行 } ctTcPr.AddNewVAlign().val = ST_VerticalJc.center;//垂直 } }
5.4、根据上述到此导出word文件效果:
using ICSharpCode.SharpZipLib.Zip; using NPOI.OpenXmlFormats.Vml.Wordprocessing; using NPOI.OpenXmlFormats.Wordprocessing; using NPOI.SS.Formula.Functions; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.XWPF.UserModel; using SixLabors.ImageSharp; using System.Data; using System.IO; using CT_Border = NPOI.OpenXmlFormats.Wordprocessing.CT_Border; namespace UsOperateWord { public class OperateWord { /// <summary> /// Word导出功能 DataTable dataTable, string cPath, string fileName, bool isSetCName = true /// </summary> public static void QRDownLoad() { //1、初始化文档 实例对应一个word文档 XWPFDocument doc = new XWPFDocument(); //设置页面格式(宽度) CT_SectPr srcpr = new CT_SectPr(); //设置A4纸纵向,如果要横向,两个值调换即可 //srcpr.pgSz.w = (ulong)11906; //srcpr.pgSz.h = (ulong)16838; //宽10厘米 高5厘米 srcpr.pgSz.w = (ulong)5670; srcpr.pgSz.h = (ulong)2835; srcpr.pgMar.left = (ulong)283.5;//左边距 0.5cm srcpr.pgMar.right = (ulong)283.5;//右边距 0.5cm srcpr.pgMar.top = (ulong)226.8;//上边距 0.4cm srcpr.pgMar.bottom = (ulong)170.1;//下边距 0.3cm doc.Document.body.sectPr = srcpr; //输出标题、创建段落 //XWPFParagraph ptitle = doc.CreateParagraph(); //ptitle.Alignment = ParagraphAlignment.LEFT; //字体居左 //XWPFRun titlerun = ptitle.CreateRun();//向该段落中添加文字 ////titlerun.SetText(fileName); //titlerun.SetText("标题"); //titlerun.IsBold = true; //titlerun.FontFamily = "微软雅黑"; //titlerun.FontSize = 30; //titlerun.SetColor("black"); 下面内容无法实现 //创建表格 行数,列数 XWPFTable table = doc.CreateTable(3, 2); //固定宽 table.GetCTTbl().AddNewTblPr().tblLayout = new CT_TblLayoutType() { type = ST_TblLayoutType.@fixed }; CT_TblBorders borders = table.GetTrPr().AddNewTblBorders(); CT_Border hBorder = borders.AddNewInsideH(); //内部行边框样式 CT_Border vBorder = borders.AddNewInsideV(); //内部列边框样式 CT_Border leftBorder = borders.AddNewLeft(); //左框线 CT_Border rightBorder = borders.AddNewRight();//右框线 CT_Border topBorder = borders.AddNewTop();//上框线 CT_Border bottomBorder = borders.AddNewBottom();//下框线 //table表格内部行边框 hBorder.val = ST_Border.dotted; hBorder.color = "green"; //table表格内部列边框 vBorder.val = ST_Border.dotted; vBorder.color = "blue"; //左边框 leftBorder.val = ST_Border.dotted; leftBorder.color = "red"; //右边框 rightBorder.val = ST_Border.dotted; rightBorder.color = "red"; //上边框 topBorder.val = ST_Border.dotted; topBorder.color = "red"; //下边框 bottomBorder.val = ST_Border.dotted; bottomBorder.color = "red"; //控制表格列宽 //页面放置内容宽度 var conwidth = srcpr.pgSz.w - srcpr.pgMar.left - srcpr.pgMar.right; table.SetColumnWidth(0, conwidth / 2); table.SetColumnWidth(1, conwidth / 2); //页面放置内容高度 var conheight = srcpr.pgSz.h - srcpr.pgMar.top - srcpr.pgMar.bottom; //var conheight1 = (ulong)Math.Ceiling(conheight / 2.1); var conheight1 = conheight / 4; //行高 table.GetRow(0).GetCTRow().AddNewTrPr().AddNewTrHeight().val = conheight1; table.GetRow(1).GetCTRow().AddNewTrPr().AddNewTrHeight().val = conheight1; table.GetRow(2).GetCTRow().AddNewTrPr().AddNewTrHeight().val = conheight1; CT_Tbl cttbl = table.GetCTTbl(); //向表格添加内容 table.GetRow(0).GetCell(1).SetText("很好1"); //AsposeWordApp asposeWordApp = new AsposeWordApp(sPath); //工作流写入,通过流的方式进行创建生成文件 MemoryStream stream = new MemoryStream(); doc.Write(stream); byte[] buffer = stream.ToArray(); string FilePath = System.AppDomain.CurrentDomain.BaseDirectory + "NPOIDemo导出word"; if (!Directory.Exists(FilePath)) { Directory.CreateDirectory(FilePath); } string fileName = "测试word文档";//保存文件名称 string sDate = DateTime.Now.ToString("yyyy年MM月dd日-HH时mm分ss秒-ffff"); FilePath = FilePath + "/" + fileName + sDate + ".doc"; FileStream Fs = new FileStream(FilePath, FileMode.OpenOrCreate); doc.Write(Fs); Fs.Close(); } } }
6、创建段落
段落为XWPFParagraph类型的实例,段落由XWPFDocument实例的使用CreateParagraph()方法生成。
XWPFParagraph MyParagraph = MyDoc.CreateParagraph();
该段落类有很多属性,用于设置与段落相关的内容。主要有以下几个方面
- BorderXXXXX属性:该值用于设置边界的样式。该属性用于获取或设置一个Borders枚举类型的值,
- FillBackgroundColor属性:背景填充的颜色。该属性获取或设置一个string类型的变量。该变量的含义是某个颜色的RGB值(在NPOI里所有的颜色都是以这种形式表示的)。例如设置为黑色则对应的代码如下:
MyParagraph.FillBackgroundColor = "#000000";
- Alignment属性:段落的对齐方式。该属性获取或设置一个ParagraphAlignment的枚举值。
- VerticalAlignment属性:文本垂直方向的对齐方式。该属性获取或设置一个TextAlignment 的枚举值。
- IndentationFirstLine属性:用于设置段落的首行缩进。该属性获取或设置一个int型变量。
这个int值并不是缩进的字数,这里可以用一个函数计算缩进的距离。
//段落缩进 返回值为对应的缩进距离 //(fontname:文字类型名称 fontsize:文字大小 fontcount:缩进数目 fontstyle:文字类型(斜体、粗体...)) int Indentation(String fontname, int fontsize, int fontnum, FontStyle fontstyle) { Graphics gp = this.CreateGraphics(); gp.PageUnit = GraphicsUnit.Point; SizeF size = gp.MeasureString("字", new Font(fontname, fontsize * 0.75F, fontstyle)); return (int)size.Width * fontnum * 10; }
示例:创建段落
var paragraph = doc.CreateParagraph(); paragraph.Alignment = ParagraphAlignment.CENTER; //字体居中 var run = paragraph.CreateRun(); run.IsBold = true; run.SetText(contend); run.FontSize = 28; run.SetFontFamily("黑体", FontCharRange.None); //设置黑体 //控制段落与其他元素的上下距离 paragraph.SpacingBeforeLines = 20;//上方距离 paragraph.SpacingAfterLines = 20;//下方距离
//设置文本高度(类似于行间距)
paragraph.TextPosition=120;
段落添加背景色
XWPFParagraph pCell = new XWPFParagraph(para, table.Body); XWPFRun run = pCell.CreateRun(); CT_Shd shd = run.GetCTR().AddNewRPr().AddNewShd();
//段落文字添加背景色 shd.fill = "FFFF00";
换页(本页未满直接写下一页)
paragraph = doc.CreateParagraph();
paragraph.CreateRun().AddBreak(BreakType.PAGE);//创建新的word文档页
同一段落中指定位置换行 (本人测试添加\n有效,不过把\n换做(char)12才可以)
//在需要换行的地方,替换 (char)12 即可,例如 var cellContent = "你好,<br />我是帅哥"; cellContent = cellContent.Replace("<br />",(char)12);
//示例:
//一段文本中包含\n的位置需要换行 string xinfo1="123123"; if (xinfo1.IndexOf('\n')>0) { string str1 = xinfo1.Substring(0, xinfo.IndexOf('\n')); string str2 = xinfo1.Substring(xinfo.IndexOf('\n') +1); run1.SetText(str1); run1.AddCarriageReturn(); run1.AppendText((char)12+str2); } else { run1.SetText(xinfo1); }
文本处理
- doc.Paragraphs 获取到文档里的所有的段落对象;
- para.ParagraphText 获取段落的文本数据;
- para.ReplaceText(要被替换的文本,替换文本) 替换段落的文本(模板能实现的关键)
7、综上了解NPOI到此,实现可以导出word中含有不同形式的表格内容
//1.A4纸12个 //2.A4纸4个 3.A4纸4个二维码在左侧 //4.单个右侧100X50 5.单个右侧模式 //6.单个左侧40*30 7.单个左侧60*30 //8.单个左侧100*50 9.单个左侧模式 //10.亚克力-单个左侧100X50
实现代码:
using UsOperateWord; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; using System.Reflection; using System.Data; using NPOI.SS.Formula.Functions; namespace ConsoleApp1 { internal class Program { static void Main(string[] args) { //导出样式 //1.A4纸12个 //2.A4纸4个 3.A4纸4个二维码在左侧 //4.单个右侧100X50 5.单个右侧模式 //6.单个左侧40*30 7.单个左侧60*30 //8.单个左侧100*50 9.单个左侧模式 //10.亚克力-单个左侧100X50 string sType = "5"; //List<Info> dataInfo = new List<Info>(); DataTable dt = new DataTable(); DataColumn dc1 = new DataColumn("Info1",typeof(string)); DataColumn dc2 = new DataColumn("Info2", typeof(string)); DataColumn dc3 = new DataColumn("Info3", typeof(string)); DataColumn dc4 = new DataColumn("Info4", typeof(string)); dt.Columns.Add(dc1); dt.Columns.Add(dc2); dt.Columns.Add(dc3); dt.Columns.Add(dc4); //3行 3和4成一个 for (var i = 0; i < 26; i++) { DataRow dr = dt.NewRow(); dr["Info1"] = "[房间" + (i + 1) + "]"; dr["Info2"] = "请扫描二维码进行故障报修。关注公众号,可随时了解当前进度"; dr["Info3"] = "报修热线:"; dr["Info4"] = "15424154121]"; dt.Rows.Add(dr); //dt.Rows.InsertAt(dr,i); //Info info = new Info { Info1 = "[房间" + (i + 1) + "]", Info2 = "请扫描二维码进行故障报修。关注公众号,可随时了解当前进度", Info3 = "报修热线:", Info4 = "15424154121" }; //dataInfo.Add(info); } //DataTable data= ListToDataTable(dataInfo); OperateWord.QRDownLoad(sType,dt); } //public class Info //{ // public string Info1 { get; set; } // public string Info2 { get; set; } // public string Info3 { get; set; } // public string Info4 { get; set; } //} /// <summary> /// C# List转换成DataTable /// </summary> /// <param name="list"></param> /// <returns></returns> public static System.Data.DataTable ListToDataTable(IList list) { System.Data.DataTable result = new System.Data.DataTable(); if (list.Count > 0) { PropertyInfo[] propertys = list[0].GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { //获取类型 Type colType = pi.PropertyType; //当类型为Nullable<>时 if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } result.Columns.Add(pi.Name, colType); } for (int i = 0; i < list.Count; i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in propertys) { object obj = pi.GetValue(list[i], null); tempList.Add(obj); } object[] array = tempList.ToArray(); result.LoadDataRow(array, true); } } return result; } } }
using ICSharpCode.SharpZipLib.Zip; using MathNet.Numerics.LinearAlgebra.Factorization; using NPOI.HSSF.UserModel; using NPOI.OpenXmlFormats.Vml; using NPOI.OpenXmlFormats.Vml.Wordprocessing; using NPOI.OpenXmlFormats.Wordprocessing; using NPOI.SS.Formula; using NPOI.SS.Formula.Functions; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.XWPF.UserModel; using SixLabors.ImageSharp; using System.Data; using System.IO; using System.Reflection.Metadata; using System.Xml.Linq; using CT_Border = NPOI.OpenXmlFormats.Wordprocessing.CT_Border; namespace UsOperateWord { public class OperateWord { /// <summary> /// Word导出功能 DataTable dataTable, string cPath, string fileName, bool isSetCName = true /// </summary> /// <param name="sType">样式</param> /// <param name="dataInfo">文本数据</param> public static void QRDownLoad(string sType, DataTable dataInfo) { #region 变量 int rowNum = 1, colNum = 2;//table表格行列数 //页面边距 左边距 0.5cm 右边距 0.5cm 上边距 0.4cm 下边距 0.3cm ulong left = (ulong)283.5, right = (ulong)283.5, top = (ulong)226.8, bottom = (ulong)170.1; //二维码、文本位置 1右边 0左边 int QRcodePos = 1; #endregion //1、初始化文档 实例对应一个word文档 XWPFDocument doc = new XWPFDocument(); //设置页面格式(宽度) CT_SectPr srcpr = new CT_SectPr(); #region 设置页面大小 //A4纸 if (sType == "2" || sType == "3") { srcpr.pgSz.w = (ulong)16838; srcpr.pgSz.h = (ulong)11906; rowNum = 2; colNum = 5; //左边距 1.5cm 右边距 1.5cm 上边距 1.5cm 下边距1.2cm left = (ulong)850.5; right = (ulong)850.5; top = (ulong)850.5; bottom = (ulong)680.4; } else if (sType == "1") { //设置A4纸纵向,如果要横向,两个值调换即可 srcpr.pgSz.w = (ulong)11906; srcpr.pgSz.h = (ulong)16838; rowNum = 6; colNum = 5; //左边距 1.2cm 右边距 1cm 上边距 0.9cm 下边距0.5cm left = (ulong)680.4; right = (ulong)567; top = (ulong)510.3; bottom = (ulong)283.5; } else if (sType == "5" || sType == "9") { //宽14厘米 高8.5厘米 srcpr.pgSz.w = (ulong)7938; srcpr.pgSz.h = (ulong)4819.5; //左边距 0.75cm 右边距 0.75cm 上边距 0.75cm 下边距0.75cm left = (ulong)425.25; right = (ulong)425.25; top = (ulong)425.25; bottom = (ulong)425.25; } else if (sType == "8" || sType == "10" || sType == "4") { //宽10厘米 高5厘米 srcpr.pgSz.w = (ulong)5670; srcpr.pgSz.h = (ulong)2835; } else if (sType == "6") { //宽4厘米 高3厘米 srcpr.pgSz.w = (ulong)2268; srcpr.pgSz.h = (ulong)1701; //左边距 0.1cm 右边距 0.1cm 上边距 0.1cm 下边距0.1cm left = (ulong)56.7; right = (ulong)56.7; top = (ulong)56.7; bottom = (ulong)56.7; } else if (sType == "7") { //宽6厘米 高3厘米 srcpr.pgSz.w = (ulong)3402; srcpr.pgSz.h = (ulong)1701; //左边距 0.1cm 右边距 0.1cm 上边距 0.1cm 下边距0.1cm left = (ulong)56.7; right = (ulong)56.7; top = (ulong)56.7; bottom = (ulong)56.7; } #endregion #region 二维码相对于文本位置 1右 0左 if (sType == "9" || sType == "3" || sType == "6" || sType == "7" || sType == "8" || sType == "10") { QRcodePos = 0; } #endregion #region 设置页边距 //页边距 srcpr.pgMar.left = left;//左边距 0.5cm srcpr.pgMar.right = right;//右边距 0.5cm srcpr.pgMar.top = top;//上边距 0.4cm srcpr.pgMar.bottom = bottom;//下边距 0.3cm doc.Document.body.sectPr = srcpr; #endregion #region 表格 ////创建表格 行数,列数 XWPFTable table = CreateTable(doc, srcpr, rowNum, colNum, sType); #region 注释内容 //doc.Document.body.sectPr = srcpr; //doc.Document.body.sectPr //设置背景图片 //具有相同属性的一个区域。 ////段落 //XWPFpCell pCell = doc.CreatepCell(); //XWPFRun run = pCell.CreateRun(); //run.SetColor("red"); //XWPFpCell MypCell = doc.CreatepCell(); //XWPFRun run = MypCell.CreateRun(); //CTShd cTShd = run.getCTR().addNewRPr().addNewShd(); //#region table表格 ////创建表格 行数,列数 //XWPFTable table = doc.CreateTable(rowNum, colNum); ////固定宽 //table.GetCTTbl().AddNewTblPr().tblLayout = new CT_TblLayoutType() { type = ST_TblLayoutType.@fixed }; //#region 单元格宽 ////控制表格列宽 ////页面放置内容宽度 //ulong conwidth = srcpr.pgSz.w - srcpr.pgMar.left - srcpr.pgMar.right; //if (colNum == 2) //{ // for (var r = 0; r < rowNum; r++) // { // table.SetColumnWidth(r, conwidth / 2); // } //} //else if (colNum == 5) //{ // if (sType == "3") // { // for (var r = 0; r < rowNum; r++) // { // table.SetColumnWidth(r, conwidth / 2); // } // } // else // { // for (var r = 0; r < rowNum; r++) // { // for (var c = 0; c < colNum; c++) // { // //设置单元格内容垂直居中 // var rowcell = table.GetRow(r).GetCell(c); // rowcell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // if (c == 2) // { // //0.5cm 283.5缇 // table.SetColumnWidth(c, (ulong)283); // } // else // { // var ss1 = conwidth - (ulong)283; // var ss12 = conwidth - 283; // var ss = (ulong)(conwidth - (ulong)283) / 4; // table.SetColumnWidth(c, (ulong)(conwidth - (ulong)283) / 4); // } // } // } // } //} //#endregion //#region 单元格高 ////页面放置内容高度 多减去0.1cm //ulong conheight = srcpr.pgSz.h - srcpr.pgMar.top - srcpr.pgMar.bottom - (ulong)56.7; //if (rowNum == 1) //{ // //行高 // table.GetRow(0).GetCTRow().AddNewTrPr().AddNewTrHeight().val = conheight; //} //else //{ // for (var r = 0; r < rowNum; r++) // { // var se = conheight / (ulong)rowNum; // table.GetRow(r).GetCTRow().AddNewTrPr().AddNewTrHeight().val = (ulong)conheight / (ulong)rowNum; // } //} //#endregion //#region 设置表格边框样式 //CT_TblBorders borders = table.GetTrPr().AddNewTblBorders(); //CT_Border hBorder = borders.AddNewInsideH(); //内部行边框样式 //CT_Border vBorder = borders.AddNewInsideV(); //内部列边框样式 //CT_Border leftBorder = borders.AddNewLeft(); //左框线 //CT_Border rightBorder = borders.AddNewRight();//右框线 //CT_Border topBorder = borders.AddNewTop();//上框线 //CT_Border bottomBorder = borders.AddNewBottom();//下框线 ////table表格内部行边框 //hBorder.val = ST_Border.dotted; //hBorder.color = "gray"; ////table表格内部列边框 //vBorder.val = ST_Border.dotted; //vBorder.color = "gray"; ////左边框 //leftBorder.val = ST_Border.dotted; //leftBorder.color = "gray"; ////右边框 //rightBorder.val = ST_Border.dotted; //rightBorder.color = "gray"; ////上边框 //topBorder.val = ST_Border.dotted; //topBorder.color = "gray"; ////下边框 //bottomBorder.val = ST_Border.dotted; //bottomBorder.color = "gray"; //#endregion //#region 向表格添加文本内容 #endregion //1.A4纸12个 //2.A4纸4个 3.A4纸4个二维码在左侧 //4.单个右侧100X50 5.单个右侧模式 //6.单个左侧40*30 7.单个左侧60*30 //8.单个左侧100*50 9.单个左侧模式 //10.亚克力-单个左侧100X50 //放置文本 for (int i = 0; i < dataInfo.Rows.Count; i++) { //一行2个二维码 if (colNum > 2) { if (i >= rowNum * 2) { if (i % (rowNum * 2) == 0) { ////创建新表格 行数,列数 table = CreateTable(doc, srcpr, rowNum, colNum, sType); } } } else { if (i >= rowNum) { ////创建新表格 行数,列数 table = CreateTable(doc, srcpr, rowNum, colNum, sType); } } //table中的文字格式设置 var para = new CT_P(); XWPFParagraph pCell = new XWPFParagraph(para, table.Body); pCell.Alignment = ParagraphAlignment.LEFT; //左对齐 pCell.VerticalAlignment = TextAlignment.CENTER; //字体居中 //pCell.SpacingAfterLines = 20; pCell.SpacingBeforeLines = 50; XWPFRun run = pCell.CreateRun(); run.FontSize = 12; run.SetFontFamily("宋体", FontCharRange.None); //设置雅黑字体 run.SetText(""); //高度 run.TextPosition = 15; DataRow dr = dataInfo.Rows[i]; for (var j = 0; j < dr.ItemArray.Count(); j++) { var sew = dr[j].ToString(); run.AppendText(dr[j].ToString()); run.AddBreak(BreakType.TEXTWRAPPING);//换行 } //二维码在文本右边 if (QRcodePos == 1) { int col = 0; if (sType == "1" || sType == "2") { if (i % 2 != 0) { col = 3; } else { col = 0; } } //段落文本放入单元格 SetParagraph(table, col, rowNum, colNum, i, pCell, sType); #region ////一行两个二维码 //if (sType == "1" || sType == "2") //{ // var index = i / 2; //第几行 // if (i >= rowNum && i < rowNum * 2) // { // index = i / 2; // } // else if (i >= rowNum * 2) // { // //一行两个二维码 // if (colNum > 2) // { // if (i % (rowNum * 2) == 0) // { // //换页 新建页 // pCell.CreateRun().AddBreak(BreakType.PAGE); // } // } // //一个二维码 // else if (colNum == 2) // { // //换页 新建页 // pCell.CreateRun().AddBreak(BreakType.PAGE); // } // //index = i - rowNum; // index = (i - (i / (rowNum * 2)) * rowNum * 2) / 2; // } // if (i % 2 == 0) // { // //放入单元格 // table.GetRow(index).GetCell(0).SetParagraph(pCell); // } // else // { // //放入单元格 // table.GetRow(index).GetCell(3).SetParagraph(pCell); // } //} //else //{ // //放入单元格 // table.GetRow(0).GetCell(0).SetParagraph(pCell); //} #endregion } //二维码在文本左边 else if (QRcodePos == 0) { int col = 1; if (sType == "3") { if (i % 2 != 0) { col = 4; } else { col = 1; } } //段落文本放入单元格 SetParagraph(table, col, rowNum, colNum, i, pCell, sType); } } #endregion //AsposeWordApp asposeWordApp = new AsposeWordApp(sPath); //工作流写入,通过流的方式进行创建生成文件 MemoryStream stream = new MemoryStream(); doc.Write(stream); byte[] buffer = stream.ToArray(); string FilePath = System.AppDomain.CurrentDomain.BaseDirectory + "NPOIDemo导出word"; if (!Directory.Exists(FilePath)) { Directory.CreateDirectory(FilePath); } string fileName = "测试word文档";//保存文件名称 string sDate = DateTime.Now.ToString("yyyy年MM月dd日-HH时mm分ss秒-ffff"); FilePath = FilePath + "/" + fileName + sDate + ".doc"; FileStream Fs = new FileStream(FilePath, FileMode.OpenOrCreate); doc.Write(Fs); Fs.Close(); } /// <summary> /// 创建表格 /// </summary> /// <param name="doc"></param> /// <param name="srcpr"></param> /// <param name="rowNum">行数</param> /// <param name="colNum">列数</param> /// <param name="sType">表格样式</param> public static XWPFTable CreateTable(XWPFDocument doc, CT_SectPr srcpr, int rowNum, int colNum, string sType) { //创建表格 行数,列数 XWPFTable table = doc.CreateTable(rowNum, colNum); //固定宽 table.GetCTTbl().AddNewTblPr().tblLayout = new CT_TblLayoutType() { type = ST_TblLayoutType.@fixed }; #region 单元格宽 //控制表格列宽 //页面放置内容宽度 ulong conwidth = srcpr.pgSz.w - srcpr.pgMar.left - srcpr.pgMar.right; if (colNum == 2) { for (var r = 0; r < rowNum; r++) { table.SetColumnWidth(0, conwidth / 2); table.SetColumnWidth(1, conwidth / 2); } } else if (colNum == 5) { for (var r = 0; r < rowNum; r++) { for (var c = 0; c < colNum; c++) { //设置单元格内容垂直居中 var rowcell = table.GetRow(r).GetCell(c); rowcell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); if (c == 2) { //0.5cm 283.5缇 table.SetColumnWidth(c, (ulong)283); } else { var ss1 = conwidth - (ulong)283; var ss12 = conwidth - 283; var ss = (ulong)(conwidth - (ulong)283) / 4; table.SetColumnWidth(c, (ulong)(conwidth - (ulong)283) / 4); } } } } #endregion #region 单元格高 //页面放置内容高度 多减去0.1cm ulong conheight = srcpr.pgSz.h - srcpr.pgMar.top - srcpr.pgMar.bottom - (ulong)56.7; if (rowNum == 1) { //行高 table.GetRow(0).GetCTRow().AddNewTrPr().AddNewTrHeight().val = conheight; } else { for (var r = 0; r < rowNum; r++) { var se = conheight / (ulong)rowNum; table.GetRow(r).GetCTRow().AddNewTrPr().AddNewTrHeight().val = (ulong)conheight / (ulong)rowNum; } } #endregion #region 设置表格边框样式 CT_TblBorders borders = table.GetTrPr().AddNewTblBorders(); CT_Border hBorder = borders.AddNewInsideH(); //内部行边框样式 CT_Border vBorder = borders.AddNewInsideV(); //内部列边框样式 CT_Border leftBorder = borders.AddNewLeft(); //左框线 CT_Border rightBorder = borders.AddNewRight();//右框线 CT_Border topBorder = borders.AddNewTop();//上框线 CT_Border bottomBorder = borders.AddNewBottom();//下框线 //table表格内部行边框 hBorder.val = ST_Border.dotted; hBorder.color = "gray"; //table表格内部列边框 vBorder.val = ST_Border.dotted; vBorder.color = "gray"; //左边框 leftBorder.val = ST_Border.dotted; leftBorder.color = "gray"; //右边框 rightBorder.val = ST_Border.dotted; rightBorder.color = "gray"; //上边框 topBorder.val = ST_Border.dotted; topBorder.color = "gray"; //下边框 bottomBorder.val = ST_Border.dotted; bottomBorder.color = "gray"; #endregion return table; } /// <summary> /// 放table内容 /// </summary> /// <param name="table">表格</param> /// <param name="col">放置文本列</param> /// <param name="rowNum">放置文本列</param> /// <param name="colNum">放置文本列</param> /// <param name="i">批量导入文本索引值</param> /// <param name="pCell">段落(内容)</param> /// <param name="sType">表格样式</param> /// <returns></returns> public static void SetParagraph(XWPFTable table, int col, int rowNum, int colNum, int i, XWPFParagraph pCell, string sType) { //一行两个二维码 if (sType == "1" || sType == "2" || sType == "3") { var index = i / 2; //第几行 if (i >= rowNum && i < rowNum * 2) { index = i / 2; } else if (i >= rowNum * 2) { if (i % (rowNum * 2) == 0) { //换页 新建页 pCell.CreateRun().AddBreak(BreakType.PAGE); } index = (i - (i / (rowNum * 2)) * rowNum * 2) / 2; } if (i % 2 == 0) { //放入单元格 table.GetRow(index).GetCell(col).SetParagraph(pCell); } else { //放入单元格 table.GetRow(index).GetCell(col).SetParagraph(pCell); } } //一行一个二维码 else { //放入单元格 table.GetRow(0).GetCell(col).SetParagraph(pCell); } } } }
8、导出word表格中插入图片
/// <summary> /// 表格插入图片 /// </summary> /// <param name="table"></param> /// <param name="Imgrow">放置行</param> /// <param name="Imgcol">放置列</param> /// <param name="fs">图片stream</param> /// <param name="ImgWidth">宽</param> /// <param name="ImgHeight">高</param> public static void Illustrate(XWPFTable table, int Imgrow, int Imgcol, FileStream fs, int ImgWidth, int ImgHeight) { var para = new CT_P(); //段落 XWPFParagraph par = new XWPFParagraph(para, table.Body); XWPFRun run = par.CreateRun(); par.Alignment = ParagraphAlignment.CENTER;//水平居中显示 //par.VerticalAlignment = TextAlignment.CENTER;//垂直居中 //par.VerticalAlignment = TextAlignment.CENTER; //Cell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);//垂直居中 //向段落插入图片1494000 宽高4.15cm //addPicture方法中的宽度和高度是EMU(英制公制单位),所有根据1 EMU = 1 / 914400英寸 = 1 / 36000 mm转化即可。 run.AddPicture(fs, (int)PictureType.PNG, Imgrow + "_" + Imgcol + ".png", ImgWidth, ImgHeight); //长和宽必须乘上9525 //向table指定行列插入图片 table.GetRow(Imgrow).GetCell(Imgcol).SetParagraph(par); }
效果如图:
9、综上涵盖知识,进一步代码完善改进此处实现效果
导出不同风格的word文档表格内容-详见第7点;
word文档表格指定行列添加文字、图片 --详见第8点;
支持表格单元格的文本设置指定行样式(加粗、颜色、大小、字体);
效果如图:
实现代码:
using UsOperateWord; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; using System.Reflection; using System.Data; using NPOI.SS.Formula.Functions; using NPOI.HPSF; using OperateWord1; using System.Text.Json.Serialization; using System.Text.Json; using System.Net.Http.Json; using Newtonsoft.Json; namespace ConsoleApp1 { internal class Program { static void Main(string[] args) { #region 用于开发测试 //var weekid = new string[] { "A4纸12个", "A4纸4个", "A4纸4个二维码在左侧", "单个右侧100X50", "单个右侧模式", "单个左侧40*30 ", "单个左侧60*30", "单个左侧100*50", "单个左侧模式", "亚克力-单个左侧100X50" }; //List<WordStyle> wordstyle = new List<WordStyle>(); //List<ParagraphStyle> ParagraphStyle1 = new List<ParagraphStyle>(); ////ParagraphStyle paragraphstyle = new ParagraphStyle() { fontcolor = "blue", isbold = true, fontfamily = "宋体", paragraphindex = 1 }; ////ParagraphStyle paragraphstyle1 = new ParagraphStyle() { fontcolor = "red", isbold = true, fontfamily = "宋体", paragraphindex = 3 }; ////ParagraphStyle1.Add(paragraphstyle); ////ParagraphStyle1.Add(paragraphstyle1); //UsWordTable b = new UsWordTable() { colnum=2,rownum=1, imgheight=6.5,imgwidth=6.5, paragraphstyle= ParagraphStyle1 }; //WordStyle w = new WordStyle() { wtype =9, pagewidth =14, pageheight =8.5, tableset = b, topmargin = 0.75, bottommargin = 0.75, leftmargin = 0.75, rightmargin = 0.75 }; //wordstyle.Add(w); //UsWordSet s = new UsWordSet() { wname="", wordstyle=wordstyle }; //string ss = JsonConvert.SerializeObject(s); #endregion #region 测试数据 word风格配置json字符串、显示文本数据、图片数据 string wordInfoJson = "{\"wname\":\"测试文档\",\"wtype\":1,\"wordstyle\":[{\"wtype\":1,\"pagewidth\":21.0,\"pageheight\":29.7,\"topmargin\":0.9,\"bottommargin\":0.5,\"leftmargin\":1.2,\"rightmargin\":1,\"tableset\":{\"rownum\":6,\"colnum\":5,\"fontfamily\":\"宋体\",\"textposition\":15,\"alignment\":1,\"fontsize\":12,\"hborderval\":5,\"hbordercolor\":\"gray\",\"vborderval\":5,\"vbordercolor\":\"gray\",\"tborderval\":5,\"tbordercolor\":\"gray\",\"bborderval\":5,\"bbordercolor\":\"gray\",\"lborderval\":5,\"lbordercolor\":\"gray\",\"rborderval\":5,\"rbordercolor\":\"gray\",\"qrcodepos\":1,\"imgwidth\":4.15,\"imgheight\":4.15,\"paragraphstyle\":[{\"paragraphindex\":1,\"fontfamily\":\"微软雅黑\",\"fontsize\":15.0,\"fontcolor\":\"red\",\"isbold\":true},{\"paragraphindex\":3,\"fontfamily\":\"微软雅黑\",\"fontsize\":10.5,\"fontcolor\":\"blue\",\"isbold\":true}]}},{\"wtype\":2,\"pagewidth\":29.7,\"pageheight\":21.0,\"topmargin\":1.5,\"bottommargin\":1.2,\"leftmargin\":1.5,\"rightmargin\":1.5,\"tableset\":{\"rownum\":2,\"colnum\":5,\"fontfamily\":\"宋体\",\"textposition\":15,\"fontsize\":12,\"hborderval\":5,\"hbordercolor\":\"gray\",\"vborderval\":5,\"vbordercolor\":\"gray\",\"tborderval\":5,\"tbordercolor\":\"gray\",\"bborderval\":5,\"bbordercolor\":\"gray\",\"lborderval\":5,\"lbordercolor\":\"gray\",\"rborderval\":5,\"rbordercolor\":\"gray\",\"qrcodepos\":1,\"imgwidth\":8,\"imgheight\":8}},\r\n{\"wtype\":3,\"pagewidth\":29.7,\"pageheight\":21.0,\"topmargin\":1.5,\"bottommargin\":1.2,\"leftmargin\":1.5,\"rightmargin\":1.5,\"tableset\":{\"rownum\":2,\"colnum\":5,\"fontfamily\":\"宋体\",\"fontsize\":12,\"hborderval\":5,\"hbordercolor\":\"gray\",\"vborderval\":5,\"vbordercolor\":\"gray\",\"tborderval\":5,\"tbordercolor\":\"gray\",\"bborderval\":5,\"bbordercolor\":\"gray\",\"lborderval\":5,\"lbordercolor\":\"gray\",\"rborderval\":5,\"rbordercolor\":\"gray\",\"qrcodepos\":0,\"imgwidth\":8,\"imgheight\":8}},{\"wtype\":4,\"pagewidth\":10.0,\"pageheight\":5.0,\"topmargin\":0.4,\"bottommargin\":0.3,\"leftmargin\":0.5,\"rightmargin\":0.5,\"tableset\":{\"rownum\":1,\"colnum\":2,\"fontfamily\":\"宋体\",\"fontsize\":12,\"hborderval\":5,\"hbordercolor\":\"gray\",\"vborderval\":5,\"vbordercolor\":\"gray\",\"tborderval\":5,\"tbordercolor\":\"gray\",\"bborderval\":5,\"bbordercolor\":\"gray\",\"lborderval\":5,\"lbordercolor\":\"gray\",\"rborderval\":5,\"rbordercolor\":\"gray\",\"qrcodepos\":1,\"imgwidth\":4.0,\"imgheight\":4.0}},{\"wtype\":5,\"pagewidth\":14.0,\"pageheight\":8.5,\"topmargin\":0.75,\"bottommargin\":0.75,\"leftmargin\":0.75,\"rightmargin\":0.75,\"tableset\":{\"rownum\":1,\"colnum\":2,\"fontfamily\":\"宋体\",\"fontsize\":12,\"hborderval\":5,\"hbordercolor\":\"gray\",\"vborderval\":5,\"vbordercolor\":\"gray\",\"tborderval\":5,\"tbordercolor\":\"gray\",\"bborderval\":5,\"bbordercolor\":\"gray\",\"lborderval\":5,\"lbordercolor\":\"gray\",\"rborderval\":5,\"rbordercolor\":\"gray\",\"qrcodepos\":1,\"imgwidth\":7.01,\"imgheight\":7.01}},{\"wtype\":6,\"pagewidth\":4.0,\"pageheight\":3.0,\"topmargin\":0.1,\"bottommargin\":0.1,\"leftmargin\":0.1,\"rightmargin\":0.1,\"tableset\":{\"rownum\":1,\"colnum\":2,\"fontfamily\":\"宋体\",\"fontsize\":7,\"hborderval\":5,\"hbordercolor\":\"gray\",\"vborderval\":5,\"vbordercolor\":\"gray\",\"tborderval\":5,\"tbordercolor\":\"gray\",\"bborderval\":5,\"bbordercolor\":\"gray\",\"lborderval\":5,\"lbordercolor\":\"gray\",\"rborderval\":5,\"rbordercolor\":\"gray\",\"qrcodepos\":0,\"imgwidth\":2.49,\"imgheight\":2.49}},{\"wtype\":7,\"pagewidth\":6.0,\"pageheight\":3.0,\"topmargin\":0.1,\"bottommargin\":0.1,\"leftmargin\":0.1,\"rightmargin\":0.1,\"tableset\":{\"rownum\":1,\"colnum\":2,\"fontfamily\":\"微软雅黑\",\"fontsize\":9,\"hborderval\":5,\"hbordercolor\":\"gray\",\"vborderval\":5,\"vbordercolor\":\"gray\",\"tborderval\":5,\"tbordercolor\":\"gray\",\"bborderval\":5,\"bbordercolor\":\"gray\",\"lborderval\":5,\"lbordercolor\":\"gray\",\"rborderval\":5,\"rbordercolor\":\"gray\",\"qrcodepos\":0,\"imgwidth\":2.72,\"imgheight\":2.72}},{\"wtype\":8,\"pagewidth\":10.0,\"pageheight\":5.0,\"topmargin\":0.4,\"bottommargin\":0.3,\"leftmargin\":0.5,\"rightmargin\":0.5,\"tableset\":{\"rownum\":1,\"colnum\":2,\"fontfamily\":\"宋体\",\"fontsize\":12,\"hborderval\":5,\"hbordercolor\":\"gray\",\"vborderval\":5,\"vbordercolor\":\"gray\",\"tborderval\":5,\"tbordercolor\":\"gray\",\"bborderval\":5,\"bbordercolor\":\"gray\",\"lborderval\":5,\"lbordercolor\":\"gray\",\"rborderval\":5,\"rbordercolor\":\"gray\",\"qrcodepos\":0,\"imgwidth\":4.0,\"imgheight\":4.0}},{\"wtype\":9,\"pagewidth\":14.0,\"pageheight\":8.5,\"topmargin\":0.75,\"bottommargin\":0.75,\"leftmargin\":0.75,\"rightmargin\":0.75,\"tableset\":{\"rownum\":1,\"colnum\":2,\"fontfamily\":\"宋体\",\"fontsize\":12,\"hborderval\":5,\"hbordercolor\":\"gray\",\"vborderval\":5,\"vbordercolor\":\"gray\",\"tborderval\":5,\"tbordercolor\":\"gray\",\"bborderval\":5,\"bbordercolor\":\"gray\",\"lborderval\":5,\"lbordercolor\":\"gray\",\"rborderval\":5,\"rbordercolor\":\"gray\",\"qrcodepos\":0,\"imgwidth\":7.01,\"imgheight\":7.01}},{\"wtype\":10,\"pagewidth\":10.0,\"pageheight\":5.0,\"topmargin\":0.4,\"bottommargin\":0.3,\"leftmargin\":0.5,\"rightmargin\":0.5,\"tableset\":{\"rownum\":1,\"colnum\":2,\"fontfamily\":\"宋体\",\"fontsize\":12,\"hborderval\":5,\"hbordercolor\":\"gray\",\"vborderval\":5,\"vbordercolor\":\"gray\",\"tborderval\":5,\"tbordercolor\":\"gray\",\"bborderval\":5,\"bbordercolor\":\"gray\",\"lborderval\":5,\"lbordercolor\":\"gray\",\"rborderval\":5,\"rbordercolor\":\"gray\",\"qrcodepos\":0,\"imgwidth\":4.0,\"imgheight\":4.0}}\r\n]}"; DataTable dt = new DataTable(); DataColumn dc1 = new DataColumn("Info1", typeof(string)); DataColumn dc2 = new DataColumn("Info2", typeof(string)); DataColumn dc3 = new DataColumn("Info3", typeof(string)); DataColumn dc4 = new DataColumn("Info4", typeof(FileStream)); dt.Columns.Add(dc1); dt.Columns.Add(dc2); dt.Columns.Add(dc3); dt.Columns.Add(dc4); //3行 3和4成一个 //图片 string FilePath = System.AppDomain.CurrentDomain.BaseDirectory + "Img"; FilePath = FilePath + "/QR.png"; for (var i = 0; i < 26; i++) { FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Read); DataRow dr = dt.NewRow(); dr["Info1"] = "[房间" + (i + 1) + "]"; dr["Info2"] = "请扫描二维码进行故障报修。关注公众号,可随时了解当前进度"; dr["Info3"] = "报修热线:"; dr["Info4"] = fs; dt.Rows.Add(dr); } #endregion 调用类库方法 #region 实现导出 //导出样式 //1.A4纸12个 //2.A4纸4个 3.A4纸4个二维码在左侧 //4.单个右侧100X50 5.单个右侧模式 //6.单个左侧40*30 7.单个左侧60*30 //8.单个左侧100*50 9.单个左侧模式 //10.亚克力-单个左侧100X50 //List<Info> dataInfo = new List<Info>(); //调用类库导出word方法 dt是填充文本数据;wordInfoJson导出word文档样式风格配置json OperateWord.QRDownLoad(dt, wordInfoJson); #endregion } #region 用于测试 //public class Info //{ // public string Info1 { get; set; } // public string Info2 { get; set; } // public string Info3 { get; set; } // public string Info4 { get; set; } //} /// <summary> /// C# List转换成DataTable /// </summary> /// <param name="list"></param> /// <returns></returns> public static System.Data.DataTable ListToDataTable(IList list) { System.Data.DataTable result = new System.Data.DataTable(); if (list.Count > 0) { PropertyInfo[] propertys = list[0].GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { //获取类型 Type colType = pi.PropertyType; //当类型为Nullable<>时 if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } result.Columns.Add(pi.Name, colType); } for (int i = 0; i < list.Count; i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in propertys) { object obj = pi.GetValue(list[i], null); tempList.Add(obj); } object[] array = tempList.ToArray(); result.LoadDataRow(array, true); } } return result; } #endregion } }
using ICSharpCode.SharpZipLib.Zip; using MathNet.Numerics.LinearAlgebra.Factorization; using Newtonsoft.Json; using NPOI.HSSF.UserModel; using NPOI.OpenXmlFormats.Vml; using NPOI.OpenXmlFormats.Vml.Wordprocessing; using NPOI.OpenXmlFormats.Wordprocessing; using NPOI.SS.Formula; using NPOI.SS.Formula.Functions; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.XWPF.UserModel; using OperateWord1; using SixLabors.ImageSharp; using System; using System.Data; using System.IO; using System.Reflection; //using System.Reflection.Metadata; using System.Text; using System.Xml.Linq; using CT_Border = NPOI.OpenXmlFormats.Wordprocessing.CT_Border; using PictureType = NPOI.XWPF.UserModel.PictureType; namespace UsOperateWord { public class OperateWord { #region Word导出功能 /// <summary> /// Word导出功能 /// </summary> /// <param name="dataInfo">文本/图片数据</param> /// <param name="wordInfoJson">导出word配置json信息</param> public static void QRDownLoad(DataTable dataInfo, string wordInfoJson) { UsWordSet UsWordSet = JsonConvert.DeserializeObject<UsWordSet>(wordInfoJson); //样式 WordStyle WordStyle = UsWordSet.wordstyle[UsWordSet.wtype - 1]; #region 变量 int rowNum = WordStyle.tableset.rownum, colNum = WordStyle.tableset.colnum;//table表格行列数 #endregion //1、初始化文档 实例对应一个word文档 XWPFDocument doc = new XWPFDocument(); //设置页面格式(宽度) CT_SectPr srcpr = new CT_SectPr(); #region 设置页面大小、二维码图片大小 srcpr.pgSz.w = getulong(WordStyle.pagewidth); srcpr.pgSz.h = getulong(WordStyle.pageheight); //二维码图片大小 1494000 宽高4.15cm int ImgWidth = getemu(WordStyle.tableset.imgwidth), ImgHeight = getemu(WordStyle.tableset.imgheight); #endregion #region 设置页边距 ulong left = getulong(WordStyle.leftmargin), right = getulong(WordStyle.rightmargin), top = getulong(WordStyle.topmargin ), bottom = getulong(WordStyle.bottommargin); //页边距 srcpr.pgMar.left = left;//左边距 0.5cm srcpr.pgMar.right = right;//右边距 0.5cm srcpr.pgMar.top = top;//上边距 0.4cm srcpr.pgMar.bottom = bottom;//下边距 0.3cm doc.Document.body.sectPr = srcpr; #endregion #region 表格 ////创建表格 行数,列数 XWPFTable table = CreateTable(doc, srcpr,WordStyle); //放置文本 for (int i = 0; i < dataInfo.Rows.Count; i++) { //一行2个二维码 if (colNum > 2) { if (i >= rowNum * 2) { if (i % (rowNum * 2) == 0) { ////创建新表格 行数,列数 table = CreateTable(doc, srcpr, WordStyle); } } } else { if (i >= rowNum) { ////创建新表格 行数,列数 table = CreateTable(doc, srcpr, WordStyle); } } //table中的文字格式设置 var para = new CT_P(); //////创建表格中的段落对象 XWPFParagraph pCell = new XWPFParagraph(para, table.Body); //设置段落背景色 //CT_Shd shd = run.GetCTR().AddNewRPr().AddNewShd(); //shd.fill = "FFFF00"; DataRow dr = dataInfo.Rows[i]; for (var j = 0; j < dr.ItemArray.Count() - 1; j++) { //创建表格中的段落对象并设置指定行特殊样式 CreateXWPFParagraph(para, table.Body, WordStyle, dr[j].ToString(),j, out XWPFParagraph pCel2); pCell = pCel2; } int Textcol = 1; int Imgcol = 1; //二维码在文本右边 if (WordStyle.tableset.qrcodepos == 1) { if (UsWordSet.wtype == 1 || UsWordSet.wtype ==2) { if (i % 2 != 0) { Textcol = 3; Imgcol = 4; } else { Textcol = 0; Imgcol = 1; } } else { Textcol = 0; Imgcol = 1; } //段落文本放入单元格 SetParagraphFun(table, Textcol, Imgcol, rowNum, i, pCell, UsWordSet.wtype, (FileStream)dr[dr.ItemArray.Count() - 1], ImgWidth, ImgHeight); } //二维码在文本左边 else if (WordStyle.tableset.qrcodepos== 0) { if (UsWordSet.wtype ==3) { if (i % 2 != 0) { Textcol = 4; Imgcol = 3; } else { Textcol = 1; Imgcol = 0; } } else { Textcol = 1; Imgcol = 0; } //段落文本放入单元格 SetParagraphFun(table, Textcol, Imgcol, rowNum, i, pCell, UsWordSet.wtype, (FileStream)dr[dr.ItemArray.Count() - 1], ImgWidth, ImgHeight); } } #endregion #region 导出word --工作流写入,通过流的方式进行创建生成文件 //AsposeWordApp asposeWordApp = new AsposeWordApp(sPath); //工作流写入,通过流的方式进行创建生成文件 MemoryStream stream = new MemoryStream(); doc.Write(stream); byte[] buffer = stream.ToArray(); string FilePath = System.AppDomain.CurrentDomain.BaseDirectory + "NPOIDemo导出word"; if (!Directory.Exists(FilePath)) { Directory.CreateDirectory(FilePath); } var weekstylearr = new string[] { "A4纸12个", "A4纸4个", "A4纸4个二维码在左侧", "单个右侧100X50", "单个右侧模式", "单个左侧40X30", "单个左侧60X30", "单个左侧100X50", "单个左侧模式", "亚克力-单个左侧100X50" }; string fileName = UsWordSet.wtype+ UsWordSet.wname;//保存文件名称 fileName = fileName + "-" + weekstylearr[UsWordSet.wtype - 1]; string sDate = DateTime.Now.ToString("yyyy年MM月dd日-HH时mm分ss秒-ffff"); FilePath = FilePath + "/" + fileName+ sDate + ".doc"; FileStream Fs = new FileStream(FilePath, FileMode.OpenOrCreate); doc.Write(Fs); Fs.Close(); #endregion } #endregion #region 1.创建表格 /// <summary> /// 创建表格 /// </summary> /// <param name="doc"></param> /// <param name="srcpr"></param> /// <param name="wordstyle">表格样式自定义10种</param> public static XWPFTable CreateTable(XWPFDocument doc, CT_SectPr srcpr, WordStyle wordstyle) { //创建表格 行数,列数 XWPFTable table = doc.CreateTable(wordstyle.tableset.rownum, wordstyle.tableset.colnum); //固定宽 table.GetCTTbl().AddNewTblPr().tblLayout = new CT_TblLayoutType() { type = ST_TblLayoutType.@fixed }; #region 单元格宽 //控制表格列宽 //页面放置内容宽度 ulong conwidth = srcpr.pgSz.w - srcpr.pgMar.left - srcpr.pgMar.right; if (wordstyle.tableset.colnum == 2) { for (var r = 0; r < wordstyle.tableset.rownum; r++) { //二维码右边 if (wordstyle.tableset.qrcodepos == 1) { table.SetColumnWidth(0, conwidth-getulong(wordstyle.tableset.imgwidth)); table.SetColumnWidth(1, getulong(wordstyle.tableset.imgwidth)); } else if(wordstyle.tableset.qrcodepos ==0) { table.SetColumnWidth(0, getulong(wordstyle.tableset.imgwidth)); table.SetColumnWidth(1, conwidth - getulong(wordstyle.tableset.imgwidth)); } //设置单元格内容垂直居中 var rowcell = table.GetRow(r).GetCell(0); var rowcel2 = table.GetRow(r).GetCell(1); rowcell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); rowcel2.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); } } else if (wordstyle.tableset.colnum == 5) { for (var r = 0; r < wordstyle.tableset.rownum; r++) { for (var c = 0; c < wordstyle.tableset.colnum; c++) { //设置单元格内容垂直居中 var rowcell = table.GetRow(r).GetCell(c); rowcell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //第二列宽度为0.5cm if (c == 2) { //0.5cm 283.5缇 table.SetColumnWidth(c, getulong(0.5)); } else { //二维码右边 if (wordstyle.tableset.qrcodepos == 1) { if (c == 1||c==4) { table.SetColumnWidth(c, getulong(wordstyle.tableset.imgwidth)); } else if(c==0||c==3) { table.SetColumnWidth(c, (conwidth- getulong(0.5))/2 - getulong(wordstyle.tableset.imgwidth)); } } else if (wordstyle.tableset.qrcodepos == 0) { if (c == 0 || c == 3) { table.SetColumnWidth(c, getulong(wordstyle.tableset.imgwidth)); } else if (c == 1 || c == 4) { table.SetColumnWidth(c, (conwidth - getulong(0.5))/2 - getulong(wordstyle.tableset.imgwidth)); } } } } } } #endregion #region 单元格高 //页面放置内容高度 多减去0.1cm ulong conheight = srcpr.pgSz.h - srcpr.pgMar.top - srcpr.pgMar.bottom - (ulong)56.7; if (wordstyle.tableset.rownum == 1) { //行高 table.GetRow(0).GetCTRow().AddNewTrPr().AddNewTrHeight().val = conheight; } else { for (var r = 0; r < wordstyle.tableset.rownum; r++) { table.GetRow(r).GetCTRow().AddNewTrPr().AddNewTrHeight().val = (ulong)conheight / (ulong)wordstyle.tableset.rownum; } } #endregion #region 设置表格边框样式 CT_TblBorders borders = table.GetTrPr().AddNewTblBorders(); CT_Border hBorder = borders.AddNewInsideH(); //内部行边框样式 CT_Border vBorder = borders.AddNewInsideV(); //内部列边框样式 CT_Border leftBorder = borders.AddNewLeft(); //左框线 CT_Border rightBorder = borders.AddNewRight();//右框线 CT_Border topBorder = borders.AddNewTop();//上框线 CT_Border bottomBorder = borders.AddNewBottom();//下框线 //table表格内部行边框 hBorder.val = wordstyle.tableset.hborderval; hBorder.color =wordstyle.tableset.hbordercolor; //table表格内部列边框 vBorder.val = wordstyle.tableset.vborderval; vBorder.color =wordstyle.tableset.vbordercolor; //左边框 leftBorder.val = wordstyle.tableset.lborderval; leftBorder.color =wordstyle.tableset.lbordercolor; //右边框 rightBorder.val = wordstyle.tableset.rborderval; rightBorder.color =wordstyle.tableset.rbordercolor; //上边框 topBorder.val = wordstyle.tableset.tborderval; topBorder.color =wordstyle.tableset.tbordercolor; //下边框 bottomBorder.val = wordstyle.tableset.bborderval; bottomBorder.color =wordstyle.tableset.bbordercolor; #endregion return table; } #endregion #region 2.创建表格中的段落对象并设置段落行样式 /// <summary> /// 创建表格中的段落对象并设置指定行特殊样式 /// </summary> /// <param name="para"></param> /// <param name="Body"></param> /// <param name="WordStyle">word样式内容</param> /// <param name="xinfo">文本内容</param> /// <param name="j">段落行索引</param> /// <param name="pCel1">表格中的段落对象</param> /// <returns></returns> public static void CreateXWPFParagraph(CT_P para, IBody Body, WordStyle WordStyle,string xinfo, int j,out XWPFParagraph pCel1) { ////创建表格中的段落对象 XWPFParagraph pCel2 = new XWPFParagraph(para,Body); XWPFRun run1 = pCel2.CreateRun(); pCel2.Alignment = WordStyle.tableset.alignment; //左对齐 pCel2.VerticalAlignment = WordStyle.tableset.verticalalignment; //字体居中 垂直对其方式 //pCell.SpacingAfterLines = 20; //pCel2.SpacingBeforeLines = 20; //有行要设置特殊样式 if (WordStyle.tableset.paragraphstyle.Count > 0) { for (var i = 0; i < WordStyle.tableset.paragraphstyle.Count; i++) { if (WordStyle.tableset.paragraphstyle[i].paragraphindex != -1 && WordStyle.tableset.paragraphstyle[i].paragraphindex - 1 == j) { run1.IsBold = WordStyle.tableset.paragraphstyle[i].isbold; run1.SetColor(WordStyle.tableset.paragraphstyle[i].fontcolor); run1.FontSize = WordStyle.tableset.paragraphstyle[i].fontsize; run1.SetFontFamily(WordStyle.tableset.paragraphstyle[i].fontfamily, FontCharRange.None); //设置雅黑字体 break; } else if (WordStyle.tableset.paragraphstyle[i].paragraphindex - 1 != j&&i == WordStyle.tableset.paragraphstyle.Count-1) { run1.IsBold = WordStyle.tableset.isbold;//是否加粗 run1.FontSize = WordStyle.tableset.fontsize; run1.SetColor(WordStyle.tableset.fontcolor); run1.SetFontFamily(WordStyle.tableset.fontfamily, FontCharRange.None); //设置雅黑字体 run1.TextPosition = WordStyle.tableset.textposition; } } } else { run1.IsBold = WordStyle.tableset.isbold;//是否加粗 run1.FontSize = WordStyle.tableset.fontsize; run1.SetColor(WordStyle.tableset.fontcolor); run1.SetFontFamily(WordStyle.tableset.fontfamily, FontCharRange.None); //设置雅黑字体 run1.TextPosition = WordStyle.tableset.textposition; } run1.SetText(xinfo); run1.AddBreak(BreakType.TEXTWRAPPING);//换行 pCel1 = pCel2; } #endregion #region 3.向table放置内容 图片-文字 /// <summary> /// 放table内容 /// </summary> /// <param name="table">表格</param> /// <param name="Textcol">放置文本列</param> /// <param name="Imgcol">放置二维码列</param> /// <param name="rowNum">放置文本行</param> /// <param name="i">批量导入文本索引值(文本list数据索引值)</param> /// <param name="pCell">段落对象(内容)</param> /// <param name="sType">表格样式</param> /// <param name="fs">二维码图片</param> /// <param name="ImgWidth">二维码宽</param> /// <param name="ImgHeight">二维码高</param> /// <returns></returns> public static void SetParagraphFun(XWPFTable table, int Textcol, int Imgcol, int rowNum, int i, XWPFParagraph pCell,int sType, FileStream fs, int ImgWidth, int ImgHeight) { //一行两个二维码 if (sType == 1 || sType ==2 || sType ==3) { var index = i / 2; //第几行 if (i >= rowNum && i < rowNum * 2) { index = i / 2; } else if (i >= rowNum * 2) { if (i % (rowNum * 2) == 0) { //换页 新建页 pCell.CreateRun().AddBreak(BreakType.PAGE); } index = (i - (i / (rowNum * 2)) * rowNum * 2) / 2; } if (i % 2 == 0) { //放入单元格 table.GetRow(index).GetCell(Textcol).SetParagraph(pCell); Illustrate(table, index, Imgcol, fs, ImgWidth, ImgHeight); } else { //放入单元格 table.GetRow(index).GetCell(Textcol).SetParagraph(pCell); Illustrate(table, index, Imgcol, fs, ImgWidth, ImgHeight); } } //一行一个二维码 else { //放入单元格 table.GetRow(0).GetCell(Textcol).SetParagraph(pCell); Illustrate(table, 0, Imgcol, fs, ImgWidth, ImgHeight); } } #endregion #region 3.1.表格插入图片 /// <summary> /// 表格插入图片 /// </summary> /// <param name="table"></param> /// <param name="Imgrow">放置行</param> /// <param name="Imgcol">放置列</param> /// <param name="fs">图片stream</param> /// <param name="ImgWidth">宽</param> /// <param name="ImgHeight">高</param> public static void Illustrate(XWPFTable table, int Imgrow, int Imgcol, FileStream fs, int ImgWidth, int ImgHeight) { var para = new CT_P(); //段落 XWPFParagraph par = new XWPFParagraph(para, table.Body); XWPFRun run = par.CreateRun(); par.Alignment = ParagraphAlignment.CENTER;//水平居中显示 //par.VerticalAlignment = TextAlignment.CENTER;//垂直居中 //par.VerticalAlignment = TextAlignment.CENTER; //Cell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);//垂直居中 //向段落插入图片1494000 宽高4.15cm //addPicture方法中的宽度和高度是EMU(英制公制单位),所有根据1 EMU = 1 / 914400英寸 = 1 / 36000 mm转化即可。 run.AddPicture(fs, (int)PictureType.PNG, Imgrow + "_" + Imgcol + ".png", ImgWidth, ImgHeight); //长和宽必须乘上9525 //向table指定行列插入图片 table.GetRow(Imgrow).GetCell(Imgcol).SetParagraph(par); } #endregion #region 4.单位换算 厘米换ulong 厘米换emu /// <summary> /// cm转换ulong /// </summary> /// <param name="c">厘米值</param> /// <returns></returns> public static ulong getulong(double c) { ulong u = (ulong)(c * 567); return u; } /// <summary> /// cm转换emu /// </summary> /// <param name="c">厘米值</param> /// <returns></returns> public static int getemu(double c) { //向段落插入图片1494000 宽高4.15cm //addPicture方法中的宽度和高度是EMU(英制公制单位),所有根据1 EMU = 1 / 914400英寸 = 1 / 36000 mm转化即可。 int u = (int)Math.Floor((c * 10) * 36000);//mm return u; } #endregion } }
using NPOI.OpenXmlFormats.Wordprocessing; using NPOI.SS.Formula.Functions; using NPOI.SS.UserModel; using NPOI.XWPF.UserModel; using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace OperateWord1 { #region 1.【UsWordSet】NIOP导出Word基本配置服务类 /// <summary> /// NIOP导出Word配置 /// </summary> public class UsWordSet { /// <summary> /// Word文档名称 /// </summary> public string wname { get; set; } /// <summary> /// word样式 ///1.A4纸12个 2.A4纸4个 3.A4纸4个二维码在左侧 4.单个右侧100X50 5.单个右侧模式 ///6.单个左侧40*30 7.单个左侧60*30 8.单个左侧100*50 9.单个左侧模式 10.亚克力-单个左侧100X50 /// </summary> public int wtype { get; set; } /// <summary> /// word文档样式 /// </summary> public List<WordStyle> wordstyle { get; set; } public UsWordSet() { wname = ""; wtype = 1; } } #endregion #region 2.【WordStyle】 自定义NIOP导出Word样板服务类 10种(当前样板主要区分设置文档页中表格的行列数) /// <summary> /// NIOP导出Word样板 10种 /// </summary> public class WordStyle { /// <summary> /// word样式 ///1.A4纸12个 2.A4纸4个 3.A4纸4个二维码在左侧 4.单个右侧100X50 5.单个右侧模式 //6.单个左侧40*30 7.单个左侧60*30 8.单个左侧100*50 9.单个左侧模式 10.亚克力-单个左侧100X50 /// </summary> public int wtype { get; set; } /// <summary> /// 页面宽 单位厘米 /// </summary> public double pagewidth { get; set; } /// <summary> /// 页面高 单位厘米 /// </summary> public double pageheight { get; set; } /// <summary> /// 页面边距 上 单位厘米 /// </summary> public double topmargin { get; set; } /// <summary> /// 页面边距 下 单位厘米 /// </summary> public double bottommargin { get; set; } /// <summary> /// 页面边距 左 单位厘米 /// </summary> public double leftmargin { get; set; } /// <summary> /// 页面边距 右 单位厘米 /// </summary> public double rightmargin { get; set; } ///// <summary> ///// Word表格配置 ///// </summary> public UsWordTable tableset { get; set; } public WordStyle() { wtype = 1; pagewidth = 21; pageheight = 29.7; tableset = new UsWordTable(); } } #endregion #region 3.【Wordtable】 表格内容配置服务类(表格样式、行列数……) /// <summary> /// Wordtable 表格内容配置 /// </summary> public class UsWordTable { /// <summary> /// 行数 /// </summary> public int rownum { get; set; } /// <summary> /// //列数 /// </summary> public int colnum { get; set; } /// <summary> /// 字体 /// </summary> public string fontfamily { get; set; } /// <summary> /// 字体大小 /// </summary> public double fontsize { get; set; } /// <summary> /// 字体yanse /// </summary> public string fontcolor { get; set; } /// <summary> /// 是否加粗 /// </summary> public bool isbold { get; set; } /// <summary> /// 行间距 /// </summary> public int textposition { get; set; } /// <summary> /// 文本对齐方式 /// </summary> public ParagraphAlignment alignment { get; set; } /// <summary> /// 文本垂直对齐方式 /// </summary> public TextAlignment verticalalignment { get; set; } #region 框线 /// <summary> /// 内横边框线型 /// </summary> public ST_Border hborderval { get; set; } /// <summary> /// 内横边框样色 /// </summary> public string hbordercolor { get; set; } /// <summary> /// 内竖边框线型 /// </summary> public ST_Border vborderval { get; set; } /// <summary> /// 内竖边框颜色 /// </summary> public string vbordercolor { get; set; } /// <summary> /// 上边框线型 /// </summary> public ST_Border tborderval { get; set; } /// <summary> /// 上边框颜色 /// </summary> public string tbordercolor { get; set; } /// <summary> /// 下边框线型 /// </summary> public ST_Border bborderval { get; set; } /// <summary> ///下边框颜色 /// </summary> public string bbordercolor { get; set; } /// <summary> /// 左边框线型 /// </summary> public ST_Border lborderval { get; set; } /// <summary> /// 左边框颜色 /// </summary> public string lbordercolor { get; set; } /// <summary> /// 右边框线型 /// </summary> public ST_Border rborderval { get; set; } /// <summary> /// 右边框颜色 /// </summary> public string rbordercolor { get; set; } #endregion /// <summary> /// 图片相对于文本位置 1右 0左 /// </summary> public int qrcodepos { get; set; } /// <summary> /// 图片宽 /// </summary> public double imgwidth { get; set; } /// <summary> /// 图片高 /// </summary> public double imgheight { get; set; } /// <summary> /// 段落特殊行设置样式 某一个段落设置特殊样式 /// </summary> public List<ParagraphStyle> paragraphstyle { get; set; } public UsWordTable() { rownum = 6; colnum = 2; fontfamily = "宋体"; fontsize = 12; fontcolor = "black"; qrcodepos = 1; imgwidth = 4; imgheight = 4; textposition = 15; isbold = false; alignment = ParagraphAlignment.LEFT; verticalalignment = TextAlignment.CENTER; vborderval = ST_Border.dotted; hborderval = ST_Border.dotted; tborderval = ST_Border.dotted; bborderval = ST_Border.dotted; lborderval = ST_Border.dotted; rborderval = ST_Border.dotted; hbordercolor = "gray"; vbordercolor = "gray"; tbordercolor = "gray"; bbordercolor = "gray"; lbordercolor = "gray"; rbordercolor = "gray"; paragraphstyle = new List<ParagraphStyle>(); } } #endregion #region 4.【ParagraphStyle】段落指定行列样式数据服务类 /// <summary> /// 段落指定行列样式数据 /// </summary> public class ParagraphStyle { /// <summary> /// 段落(行)索引 /// </summary> public int paragraphindex { get; set; } /// <summary> /// 字体 /// </summary> public string fontfamily { get; set; } /// <summary> /// 字体大小 /// </summary> public double fontsize { get; set; } /// <summary> /// 字体颜色 /// </summary> public string fontcolor { get; set; } /// <summary> /// 是否加粗 /// </summary> public bool isbold { get; set; } public ParagraphStyle() { paragraphindex = -1; fontfamily = "宋体"; fontsize = 12; fontcolor = "black"; isbold = false; } } #endregion }
10、NPOI读取Word文档
//1、初始化文档 实例对应一个word文档 //XWPFDocument doc = new XWPFDocument(); XWPFDocument doc; //亚克力模板 if (UsWordSet.wtype== 10) {
//本地word文档 var template = @"亚克力-单个左侧100X50模板.docx"; using (var rs = File.OpenRead(template)) { doc = new XWPFDocument(rs); } } else { doc = new XWPFDocument(); }
npoi打开过程遇到问题:
1、
问题原因--解决方法:
NPOI操作word文档只可操作2003版的word,或者2007版的docx文档,如果是其他版本的word文档,在读取word模板文档时会出现Exception: Wrong Local header signature: 0xE011CFD0的错误,解决这个错误,只要将word文档另存为docx格式的就可以了
参考文献:.Net NPOI Word模板关键内容替换 - 代码先锋网 (codeleading.com)
2、
问题原因--解决方法:该文档本地office正打开着,关闭即可
11、进一步完善后实现代码
与上一版区别:
1、显示文本信息对于空值进行过滤
2、某一段落中根据\n进行指定位置换行(段落中换行)
3、传入的数据list类型,上一版本为datetable类型
4、传入图片通过获取图片的byte字节数组进行转stream后进行图片插入、上一版本为直接通过路径获取到filestream进行图片插入
代码详情:
///************************************************************************ ///作者代号:CF ///创建日期:2023-02-06 ///功能描述:NPOI导出word功能 ///修改时间: ///修改代号: ///修改内容: ///************************************************************************ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NPOI.HPSF; using Org.BouncyCastle.Utilities; using System.Collections.Generic; using System.Data; using System.IO; using System.IO.Pipes; using System.Linq; using System.Text.RegularExpressions; using Us.Core.Plug.UsIOP.Entity; using Us.Standard.UsTools; using Us.Standard.UsTools.Core; namespace Us.Core.FrameWork.UsDBasic { public class UsKWordExportTools { #region 1.导出Word文件 /// <summary> /// 导出Word文件 /// </summary> /// <param name="set"></param> /// <param name="dt"></param> /// <returns></returns> public static APIResult ExportWord(KIOP_QrCode_Export_Setting set, DataTable dt) { APIResult r = new APIResult(); r= ExportWord_NPOI(dt,set); return r; } #endregion /// <summary> /// 导出word功能 0成功 /// </summary> /// <param name="dt">数据</param> /// <param name="k_web_config">KIOP网站配置</param> /// <param name="wordname">导出word文档名称</param> /// <param name="saveurl">存放word文档地址</param> /// <returns></returns> public static APIResult ExportWord_NPOI(DataTable dt, KIOP_QrCode_Export_Setting qrcode_export_setting) { APIResult res = new APIResult(); //数据整理 ExportWordBasicInfo basicInfo = new ExportWordBasicInfo() { wtype= qrcode_export_setting.oms_qr_type.Ext_ToInt(), saveurl= qrcode_export_setting.stpath.Ext_IsDBNull()}; ExportWordData exportworddata = new ExportWordData() { Remark= qrcode_export_setting.oms_qr_info.Ext_IsDBNull() , Phone= qrcode_export_setting.oms_tel.Ext_IsDBNull() }; if (dt.Rows.Count>0) { for (int i = 0; i < dt.Rows.Count; i++) { //获取数据行 DataRow dr = dt.Rows[i]; //遍历数据行 (一行有多个数据值) for (var j = 0; j < dr.ItemArray.Count(); j++) { exportworddata.Title = dr["Title"].Ext_IsDBNull(); exportworddata.CTitle = dr["CTitle"].Ext_IsDBNull(); exportworddata.QRStream = getQRStream(dr["QrCode"].Ext_IsDBNull(), qrcode_export_setting.oms_qr_images); basicInfo.exportworddata.Add(exportworddata); } } } //获取NPOI导出word功能数据json配置 //ExportWordConfig jsConfig = UsKCoreConfig.UsGetConfig<ExportWordConfig>("/usconfig/usnpoiwordconfig.json"); string wordConfigJson = UsKCoreConfig.UsGetJSONKeyV2("/usconfig/usnpoiwordconfig.json"); wordConfigJson = wordConfigJson.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", ""); ExportWordConfig jsConfig = JsonConvert.DeserializeObject<ExportWordConfig>(wordConfigJson); //导出Word res = OperateWord_NPOI.WordExport(basicInfo, jsConfig); return res; } /// <summary> /// 获取二维码Stream /// </summary> /// <param name="QrCode"></param> /// <returns></returns> public static byte[] getQRStream(string QrCode,string QrUrl) { //FileStream stream = null; byte[] byteInfo; //FileStream stream = new FileStream("", FileMode.OpenOrCreate); if (!string.IsNullOrEmpty(QrUrl)) { //stream = UsKQRTools.UsQrCode_Stream(QrCode, QrUrl); byteInfo = UsKQRTools.UsQrCode_byte(QrCode, QrUrl); } else { //stream = UsKQRTools.UsQrCode_Stream(QrCode, ""); byteInfo = UsKQRTools.UsQrCode_byte(QrCode, ""); } //return stream; return byteInfo; } } }
///************************************************************************ ///作者代号:CF ///创建日期:2023-02-06 ///功能描述:NPOI导出word操作类库 ///修改时间: ///修改代号: ///修改内容: ///************************************************************************ using Microsoft.CodeAnalysis; using Newtonsoft.Json; using NPOI.OpenXmlFormats.Wordprocessing; using NPOI.SS.Formula.Functions; using NPOI.SS.UserModel; using NPOI.XWPF.UserModel; using Org.BouncyCastle.Utilities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Us.Standard.UsTools; using CT_Border = NPOI.OpenXmlFormats.Wordprocessing.CT_Border; using PictureType = NPOI.XWPF.UserModel.PictureType; namespace Us.Core.FrameWork.UsDBasic { public class OperateWord_NPOI { #region Word导出功能 /// <summary> /// Word导出功能 /// </summary> /// <param name="wordbasicinfo">word基本信息</param> /// <param name="wtype">选择导出word模板</param> /// <param name="wordInfoJson">导出word配置json信息</param> public static APIResult WordExport(ExportWordBasicInfo wordbasicinfo, ExportWordConfig ExportWordConfig) { APIResult res = new APIResult(); XWPFDocument d = new XWPFDocument(); //ExportWordConfig ExportWordConfig = JsonConvert.DeserializeObject<ExportWordConfig>(wordConfigJson); ExportWordStyle WordStyle; //用户选择的样式 if (wordbasicinfo.wtype > 0 && wordbasicinfo.wtype <= ExportWordConfig.wordstyle.Count) { WordStyle = ExportWordConfig.wordstyle[wordbasicinfo.wtype - 1]; } else { res.result = 1; res.msg = "选择模板样式不存在,请重新选择"; return res; } #region 变量 int rowNum = WordStyle.tableset.rownum, colNum = WordStyle.tableset.colnum;//table表格行列数 byte[] byteInfo = null;//二维码 #endregion //1、初始化文档 实例对应一个word文档 XWPFDocument doc = new XWPFDocument(); //设置页面格式(宽度) CT_SectPr srcpr = new CT_SectPr(); #region 设置页面大小、二维码图片大小 srcpr.pgSz.w = getulong(WordStyle.pagewidth); srcpr.pgSz.h = getulong(WordStyle.pageheight); //二维码图片大小 1494000 宽高4.15cm int ImgWidth = getemu(WordStyle.tableset.imgwidth), ImgHeight = getemu(WordStyle.tableset.imgheight); #endregion #region 设置页边距 ulong left = getulong(WordStyle.leftmargin), right = getulong(WordStyle.rightmargin), top = getulong(WordStyle.topmargin ), bottom = getulong(WordStyle.bottommargin); //页边距 srcpr.pgMar.left = left;//左边距 0.5cm srcpr.pgMar.right = right;//右边距 0.5cm srcpr.pgMar.top = top;//上边距 0.4cm srcpr.pgMar.bottom = bottom;//下边距 0.3cm doc.Document.body.sectPr = srcpr; #endregion #region 表格 ////创建表格 行数,列数 XWPFTable table = CreateTable(doc, srcpr, WordStyle); //放置文本 for (int i = 0; i < wordbasicinfo.exportworddata.Count; i++) { //一行2个二维码 if (colNum > 2) { if (i >= rowNum * 2) { if (i % (rowNum * 2) == 0) { ////创建新表格 行数,列数 table = CreateTable(doc, srcpr, WordStyle); } } } else { if (i >= rowNum) { ////创建新表格 行数,列数 table = CreateTable(doc, srcpr, WordStyle); } } //table中的文字格式设置 var para = new CT_P(); //////创建表格中的段落对象 XWPFParagraph pCell = new XWPFParagraph(para, table.Body); //设置段落背景色 //CT_Shd shd = run.GetCTR().AddNewRPr().AddNewShd(); //shd.fill = "FFFF00"; ExportWordData w = wordbasicinfo.exportworddata[i]; PropertyInfo[] props = typeof(ExportWordData).GetProperties();//实体的字段列表 for (var j = 0; j < props.Count(); j++) { string Text = "";//文本 if (props[j].Name != "QRStream") { Text = props[j].GetValue(w) as string; } else { //图片stream byteInfo = props[j].GetValue(w) as byte[]; } //创建表格中的段落对象并设置指定行特殊样式 CreateXWPFParagraph(para, table.Body, WordStyle, Text, j, props.Count()-1, out XWPFParagraph pCel2); pCell = pCel2; } int Textcol = 1; int Imgcol = 1; //二维码在文本右边 if (WordStyle.tableset.qrcodepos == 1) { if (wordbasicinfo.wtype == 1 || wordbasicinfo.wtype == 2) { if (i % 2 != 0) { Textcol = 3; Imgcol = 4; } else { Textcol = 0; Imgcol = 1; } } else { Textcol = 0; Imgcol = 1; } //段落文本放入单元格 SetParagraphFun(table, Textcol, Imgcol, rowNum, i, pCell, wordbasicinfo.wtype, byteInfo, ImgWidth, ImgHeight); } //二维码在文本左边 else if (WordStyle.tableset.qrcodepos == 0) { if (wordbasicinfo.wtype == 3) { if (i % 2 != 0) { Textcol = 4; Imgcol = 3; } else { Textcol = 1; Imgcol = 0; } } else { Textcol = 1; Imgcol = 0; } //段落文本放入单元格 SetParagraphFun(table, Textcol, Imgcol, rowNum, i, pCell, wordbasicinfo.wtype, byteInfo, ImgWidth, ImgHeight); } } #endregion #region 导出word --工作流写入,通过流的方式进行创建生成文件 //工作流写入,通过流的方式进行创建生成文件 MemoryStream stream = new MemoryStream(); doc.Write(stream); byte[] buffer = stream.ToArray(); string FilePath = wordbasicinfo.saveurl; FileStream Fs = new FileStream(FilePath, FileMode.OpenOrCreate); doc.Write(Fs); Fs.Close(); res.result = 0; res.msg = "导出成功"; return res; #endregion } #endregion #region 1.创建表格 /// <summary> /// 创建表格 /// </summary> /// <param name="doc"></param> /// <param name="srcpr"></param> /// <param name="wordstyle">表格样式自定义10种</param> public static XWPFTable CreateTable(XWPFDocument doc, CT_SectPr srcpr, ExportWordStyle wordstyle) { //创建表格 行数,列数 XWPFTable table = doc.CreateTable(wordstyle.tableset.rownum, wordstyle.tableset.colnum); //固定宽 table.GetCTTbl().AddNewTblPr().tblLayout = new CT_TblLayoutType() { type = ST_TblLayoutType.@fixed }; #region 单元格宽 //控制表格列宽 //页面放置内容宽度 ulong conwidth = srcpr.pgSz.w - srcpr.pgMar.left - srcpr.pgMar.right; if (wordstyle.tableset.colnum == 2) { for (var r = 0; r < wordstyle.tableset.rownum; r++) { //二维码右边 if (wordstyle.tableset.qrcodepos == 1) { table.SetColumnWidth(0, conwidth - getulong(wordstyle.tableset.imgwidth)); table.SetColumnWidth(1, getulong(wordstyle.tableset.imgwidth)); } else if (wordstyle.tableset.qrcodepos == 0) { table.SetColumnWidth(0, getulong(wordstyle.tableset.imgwidth)); table.SetColumnWidth(1, conwidth - getulong(wordstyle.tableset.imgwidth)); } //设置单元格内容垂直居中 var rowcell = table.GetRow(r).GetCell(0); var rowcel2 = table.GetRow(r).GetCell(1); rowcell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); rowcel2.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); } } else if (wordstyle.tableset.colnum == 5) { if (wordstyle.tableset.rownum != 6) { for (var r = 0; r < wordstyle.tableset.rownum; r++) { for (var c = 0; c < wordstyle.tableset.colnum; c++) { //设置单元格内容垂直居中 var rowcell = table.GetRow(r).GetCell(c); rowcell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //第二列宽度为0.5cm if (c == 2) { //0.5cm 283.5缇 table.SetColumnWidth(c, getulong(0.5)); } else { //二维码右边 if (wordstyle.tableset.qrcodepos == 1) { if (c == 1 || c == 4) { //table.SetColumnWidth(c, getulong(wordstyle.tableset.imgwidth)); table.SetColumnWidth(c, (conwidth - getulong(0.5)) / 2 - ((conwidth - getulong(0.5)) / 8)); } else if (c == 0 || c == 3) { //table.SetColumnWidth(c, (conwidth - getulong(0.5)) / 2 - getulong(wordstyle.tableset.imgwidth)); table.SetColumnWidth(c, (conwidth - getulong(0.5)) / 8); } } else if (wordstyle.tableset.qrcodepos == 0) { if (c == 0 || c == 3) { //table.SetColumnWidth(c, getulong(wordstyle.tableset.imgwidth)); table.SetColumnWidth(c, (conwidth - getulong(0.5)) / 2 - ((conwidth - getulong(0.5)) / 8)); } else if (c == 1 || c == 4) { //table.SetColumnWidth(c, (conwidth - getulong(0.5)) / 2 - getulong(wordstyle.tableset.imgwidth)); table.SetColumnWidth(c, (conwidth - getulong(0.5)) / 8); } } } } } } else { for (var r = 0; r < wordstyle.tableset.rownum; r++) { for (var c = 0; c < wordstyle.tableset.colnum; c++) { //设置单元格内容垂直居中 var rowcell = table.GetRow(r).GetCell(c); rowcell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //第二列宽度为0.5cm if (c == 2) { //0.5cm 283.5缇 table.SetColumnWidth(c, getulong(0.5)); } else { table.SetColumnWidth(c, (conwidth - getulong(0.5)) / 4); } } } } } #endregion #region 单元格高 //页面放置内容高度 多减去0.1cm ulong conheight = srcpr.pgSz.h - srcpr.pgMar.top - srcpr.pgMar.bottom - (ulong)56.7; if (wordstyle.tableset.rownum == 1) { //行高 table.GetRow(0).GetCTRow().AddNewTrPr().AddNewTrHeight().val = conheight; } else { for (var r = 0; r < wordstyle.tableset.rownum; r++) { table.GetRow(r).GetCTRow().AddNewTrPr().AddNewTrHeight().val = (ulong)conheight / (ulong)wordstyle.tableset.rownum; } } #endregion #region 设置表格边框样式 CT_TblBorders borders = table.GetTrPr().AddNewTblBorders(); CT_Border hBorder = borders.AddNewInsideH(); //内部行边框样式 CT_Border vBorder = borders.AddNewInsideV(); //内部列边框样式 CT_Border leftBorder = borders.AddNewLeft(); //左框线 CT_Border rightBorder = borders.AddNewRight();//右框线 CT_Border topBorder = borders.AddNewTop();//上框线 CT_Border bottomBorder = borders.AddNewBottom();//下框线 //table表格内部行边框 hBorder.val = wordstyle.tableset.hborderval; hBorder.color = wordstyle.tableset.hbordercolor; //table表格内部列边框 vBorder.val = wordstyle.tableset.vborderval; vBorder.color = wordstyle.tableset.vbordercolor; //左边框 leftBorder.val = wordstyle.tableset.lborderval; leftBorder.color = wordstyle.tableset.lbordercolor; //右边框 rightBorder.val = wordstyle.tableset.rborderval; rightBorder.color = wordstyle.tableset.rbordercolor; //上边框 topBorder.val = wordstyle.tableset.tborderval; topBorder.color = wordstyle.tableset.tbordercolor; //下边框 bottomBorder.val = wordstyle.tableset.bborderval; bottomBorder.color = wordstyle.tableset.bbordercolor; #endregion return table; } #endregion #region 2.创建表格中的段落对象并设置段落行样式 /// <summary> /// 创建表格中的段落对象并设置指定行特殊样式 /// </summary> /// <param name="para"></param> /// <param name="Body"></param> /// <param name="WordStyle">word样式内容</param> /// <param name="xinfo">文本内容</param> /// <param name="j">段落行索引</param> /// <param name="tcount">提示文本总行数</param> /// <param name="pCel1">表格中的段落对象</param> /// <returns></returns> public static void CreateXWPFParagraph(CT_P para, IBody Body, ExportWordStyle WordStyle, string xinfo, int j,int tcount, out XWPFParagraph pCel1) { ////创建表格中的段落对象 XWPFParagraph pCel2 = new XWPFParagraph(para, Body); XWPFRun run1 = pCel2.CreateRun(); pCel2.Alignment = WordStyle.tableset.alignment; //左对齐 //pCel2.VerticalAlignment = WordStyle.tableset.verticalalignment; //字体居中 垂直对其方式 //pCell.SpacingAfterLines = 20; //pCel2.SpacingBeforeLines = 20; if (!string.IsNullOrEmpty(xinfo)) { //有行要设置特殊样式 if (WordStyle.tableset.paragraphstyle.Count > 0) { for (var i = 0; i < WordStyle.tableset.paragraphstyle.Count; i++) { if (WordStyle.tableset.paragraphstyle[i].paragraphindex >= 0 && WordStyle.tableset.paragraphstyle[i].paragraphindex - 1 == j) { run1.IsBold = WordStyle.tableset.paragraphstyle[i].isbold; run1.SetColor(WordStyle.tableset.paragraphstyle[i].fontcolor); run1.FontSize = WordStyle.tableset.paragraphstyle[i].fontsize; run1.SetFontFamily(WordStyle.tableset.paragraphstyle[i].fontfamily, FontCharRange.None); //设置雅黑字体 run1.TextPosition = WordStyle.tableset.textposition; break; } else if (WordStyle.tableset.paragraphstyle[i].paragraphindex - 1 != j && i == WordStyle.tableset.paragraphstyle.Count - 1) { run1.IsBold = WordStyle.tableset.isbold;//是否加粗 run1.FontSize = WordStyle.tableset.fontsize; run1.SetColor(WordStyle.tableset.fontcolor); run1.SetFontFamily(WordStyle.tableset.fontfamily, FontCharRange.None); //设置雅黑字体 run1.TextPosition = WordStyle.tableset.textposition; } } } else { run1.IsBold = WordStyle.tableset.isbold;//是否加粗 run1.FontSize = WordStyle.tableset.fontsize; run1.SetColor(WordStyle.tableset.fontcolor); run1.SetFontFamily(WordStyle.tableset.fontfamily, FontCharRange.None); //设置雅黑字体 run1.TextPosition = WordStyle.tableset.textposition; } //文本中包含\n需要换行 if (xinfo.IndexOf('\n')>0) { string str1 = xinfo.Substring(0, xinfo.IndexOf('\n')); string str2 = xinfo.Substring(xinfo.IndexOf('\n') +1); run1.SetText(str1); run1.AddCarriageReturn(); run1.AppendText((char)12+str2); } else { run1.SetText(xinfo); } //run1.SetText(xinfo); //换行 并且最后一行不需要添加换行 if(j+1< tcount) { run1.AddBreak(BreakType.TEXTWRAPPING);//换行 } } pCel1 = pCel2; } #endregion #region 3.向table放置内容 图片-文字 /// <summary> /// 放table内容 /// </summary> /// <param name="table">表格</param> /// <param name="Textcol">放置文本列</param> /// <param name="Imgcol">放置二维码列</param> /// <param name="rowNum">放置文本行</param> /// <param name="i">批量导入文本索引值(文本list数据索引值)</param> /// <param name="pCell">段落对象(内容)</param> /// <param name="sType">表格样式</param> /// <param name="fs">二维码图片</param> /// <param name="ImgWidth">二维码宽</param> /// <param name="ImgHeight">二维码高</param> /// <returns></returns> public static void SetParagraphFun(XWPFTable table, int Textcol, int Imgcol, int rowNum, int i, XWPFParagraph pCell, int sType, byte[] fs, int ImgWidth, int ImgHeight) { //一行两个二维码 if (sType == 1 || sType == 2 || sType == 3) { var index = i / 2; //第几行 if (i >= rowNum && i < rowNum * 2) { index = i / 2; } else if (i >= rowNum * 2) { if (i % (rowNum * 2) == 0) { //换页 新建页 pCell.CreateRun().AddBreak(BreakType.PAGE); } index = (i - (i / (rowNum * 2)) * rowNum * 2) / 2; } if (i % 2 == 0) { //放入单元格 table.GetRow(index).GetCell(Textcol).SetParagraph(pCell); if (fs != null) { Illustrate(table, index, Imgcol, fs, ImgWidth, ImgHeight); } } else { //放入单元格 table.GetRow(index).GetCell(Textcol).SetParagraph(pCell); if (fs != null) { Illustrate(table, index, Imgcol, fs, ImgWidth, ImgHeight); } } } //一行一个二维码 else { //放入单元格 table.GetRow(0).GetCell(Textcol).SetParagraph(pCell); if (fs != null) { Illustrate(table, 0, Imgcol, fs, ImgWidth, ImgHeight); } } } #endregion #region 3.1.表格插入图片 /// <summary> /// 表格插入图片 /// </summary> /// <param name="table"></param> /// <param name="Imgrow">放置行</param> /// <param name="Imgcol">放置列</param> /// <param name="fs">图片stream</param> /// <param name="ImgWidth">宽</param> /// <param name="ImgHeight">高</param> public static void Illustrate(XWPFTable table, int Imgrow, int Imgcol, byte[] fs, int ImgWidth, int ImgHeight) { var para = new CT_P(); //段落 XWPFParagraph par = new XWPFParagraph(para, table.Body); XWPFRun run = par.CreateRun(); par.Alignment = ParagraphAlignment.CENTER;//水平居中显示 //par.VerticalAlignment = TextAlignment.CENTER;//垂直居中 //Cell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);//垂直居中 //向段落插入图片 Stream stream = new MemoryStream(fs); run.AddPicture(stream, (int)PictureType.PNG, Imgrow + "_" + Imgcol + ".png", ImgWidth, ImgHeight); //向table指定行列插入图片 table.GetRow(Imgrow).GetCell(Imgcol).SetParagraph(par); } #endregion #region 单位转换 #region 4.单位换算 厘米换ulong 厘米换emu /// <summary> /// cm转换ulong /// </summary> /// <param name="c">厘米值</param> /// <returns></returns> public static ulong getulong(double c) { ulong u = (ulong)(c * 567); return u; } /// <summary> /// cm转换emu /// </summary> /// <param name="c">厘米值</param> /// <returns></returns> public static int getemu(double c) { //向段落插入图片1494000 宽高4.15cm //addPicture方法中的宽度和高度是EMU(英制公制单位),所有根据1 EMU = 1 / 914400英寸 = 1 / 36000 mm转化即可。 int u = (int)Math.Floor((c * 10) * 36000);//mm return u; } #endregion #endregion } }
///************************************************************************ ///作者代号:CF ///创建日期:2023-02-06 ///功能描述:NPOI导出word基础类 ///修改时间: ///修改代号: ///修改内容: ///************************************************************************ using NPOI.OpenXmlFormats.Wordprocessing; using NPOI.SS.Formula.Functions; using NPOI.SS.UserModel; using NPOI.XWPF.UserModel; using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace Us.Core.FrameWork.UsDBasic { public class NPOIBasic { } #region 1.【ExportWordConfig】NIOP导出Word基本配置服务类 /// <summary> /// NIOP导出Word配置 /// </summary> public class ExportWordConfig { /// <summary> /// word文档样式 /// </summary> public List<ExportWordStyle> wordstyle { get; set; } public ExportWordConfig() { wordstyle = new List<ExportWordStyle>(); } } #endregion #region 2.【ExportWordStyle】 自定义NIOP导出Word样板服务类 10种(当前样板主要区分设置文档页中表格的行列数) /// <summary> /// NIOP导出Word样板 10种 /// </summary> public class ExportWordStyle { /// <summary> /// word样式 ///1.A4纸12个 2.A4纸4个 3.A4纸4个二维码在左侧 4.单个右侧100X50 5.单个右侧模式 //6.单个左侧40*30 7.单个左侧60*30 8.单个左侧100*50 9.单个左侧模式 10.亚克力-单个左侧100X50 /// </summary> public int wtype { get; set; } /// <summary> /// 页面宽 单位厘米 /// </summary> public double pagewidth { get; set; } /// <summary> /// 页面高 单位厘米 /// </summary> public double pageheight { get; set; } /// <summary> /// 页面边距 上 单位厘米 /// </summary> public double topmargin { get; set; } /// <summary> /// 页面边距 下 单位厘米 /// </summary> public double bottommargin { get; set; } /// <summary> /// 页面边距 左 单位厘米 /// </summary> public double leftmargin { get; set; } /// <summary> /// 页面边距 右 单位厘米 /// </summary> public double rightmargin { get; set; } ///// <summary> ///// Word表格配置 ///// </summary> public ExportWordTable tableset { get; set; } public ExportWordStyle() { wtype = 1; pagewidth = 21; pageheight = 29.7; topmargin = 0.9; bottommargin = 0.5; leftmargin = 1.2; rightmargin = 1; tableset = new ExportWordTable(); } } #endregion #region 3.【ExportWordTable】 表格内容配置服务类(表格样式、行列数……) /// <summary> /// ExportWordTable 表格内容配置 /// </summary> public class ExportWordTable { /// <summary> /// 行数 /// </summary> public int rownum { get; set; } /// <summary> /// //列数 /// </summary> public int colnum { get; set; } /// <summary> /// 字体 /// </summary> public string fontfamily { get; set; } /// <summary> /// 字体大小 /// </summary> public double fontsize { get; set; } /// <summary> /// 字体颜色 /// </summary> public string fontcolor { get; set; } /// <summary> /// 是否加粗 /// </summary> public bool isbold { get; set; } /// <summary> /// 行间距 /// </summary> public int textposition { get; set; } /// <summary> /// 文本对齐方式 /// </summary> public ParagraphAlignment alignment { get; set; } /// <summary> /// 文本垂直对齐方式 /// </summary> public TextAlignment verticalalignment { get; set; } #region 框线 /// <summary> /// 内横边框线型 /// </summary> public ST_Border hborderval { get; set; } /// <summary> /// 内横边框样色 /// </summary> public string hbordercolor { get; set; } /// <summary> /// 内竖边框线型 /// </summary> public ST_Border vborderval { get; set; } /// <summary> /// 内竖边框颜色 /// </summary> public string vbordercolor { get; set; } /// <summary> /// 上边框线型 /// </summary> public ST_Border tborderval { get; set; } /// <summary> /// 上边框颜色 /// </summary> public string tbordercolor { get; set; } /// <summary> /// 下边框线型 /// </summary> public ST_Border bborderval { get; set; } /// <summary> ///下边框颜色 /// </summary> public string bbordercolor { get; set; } /// <summary> /// 左边框线型 /// </summary> public ST_Border lborderval { get; set; } /// <summary> /// 左边框颜色 /// </summary> public string lbordercolor { get; set; } /// <summary> /// 右边框线型 /// </summary> public ST_Border rborderval { get; set; } /// <summary> /// 右边框颜色 /// </summary> public string rbordercolor { get; set; } #endregion /// <summary> /// 图片相对于文本位置 1右 0左 /// </summary> public int qrcodepos { get; set; } /// <summary> /// 图片宽 /// </summary> public double imgwidth { get; set; } /// <summary> /// 图片高 /// </summary> public double imgheight { get; set; } /// <summary> /// 段落特殊行设置样式 某一个段落设置特殊样式 /// </summary> public List<ExportWordParagraphStyle> paragraphstyle { get; set; } public ExportWordTable() { rownum = 6; colnum = 2; fontfamily = "宋体"; fontsize = 12; fontcolor = "black"; qrcodepos = 1; imgwidth = 4; imgheight = 4; textposition = 15; isbold = false; alignment = ParagraphAlignment.LEFT; verticalalignment = TextAlignment.CENTER; vborderval = ST_Border.dotted; hborderval = ST_Border.dotted; tborderval = ST_Border.dotted; bborderval = ST_Border.dotted; lborderval = ST_Border.dotted; rborderval = ST_Border.dotted; hbordercolor = "gray"; vbordercolor = "gray"; tbordercolor = "gray"; bbordercolor = "gray"; lbordercolor = "gray"; rbordercolor = "gray"; paragraphstyle = new List<ExportWordParagraphStyle>(); } } #endregion #region 4.【ExportWordParagraphStyle】段落指定行列样式数据服务类 /// <summary> /// 段落指定行列样式数据 /// </summary> public class ExportWordParagraphStyle { /// <summary> /// 段落(行)索引 /// </summary> public int paragraphindex { get; set; } /// <summary> /// 字体 /// </summary> public string fontfamily { get; set; } /// <summary> /// 字体大小 /// </summary> public double fontsize { get; set; } /// <summary> /// 字体颜色 /// </summary> public string fontcolor { get; set; } /// <summary> /// 是否加粗 /// </summary> public bool isbold { get; set; } public ExportWordParagraphStyle() { paragraphindex = -1; fontfamily = "宋体"; fontsize = 12; fontcolor = "black"; isbold = false; } } #endregion #region 导出word基本信息配置 public class ExportWordBasicInfo { /// <summary> /// Word文档名称 /// </summary> public string wname { get; set; } /// <summary> /// word样式 ///1.A4纸12个 2.A4纸4个 3.A4纸4个二维码在左侧 4.单个右侧100X50 5.单个右侧模式 ///6.单个左侧40*30 7.单个左侧60*30 8.单个左侧100*50 9.单个左侧模式 10.亚克力-单个左侧100X50 /// </summary> public int wtype { get; set; } /// <summary> /// word保存路径 /// </summary> public string saveurl { get; set; } /// <summary> /// 内容 /// </summary> public List<ExportWordData> exportworddata { get; set; } public ExportWordBasicInfo() { wname = ""; wtype = 1; exportworddata = new List<ExportWordData>(); saveurl = ""; } } #endregion #region 5.文本、图片数据 public class ExportWordData { /// <summary> /// 教室名称-主标题 /// </summary> public string Title { get; set; } /// <summary> /// 教室编号-副标题 /// </summary> public string CTitle { get; set; } /// <summary> /// 备注 -二维码说明文字 /// </summary> public string Remark { get; set; } /// <summary> /// 联系电话 /// </summary> public string Phone { get; set; } /// <summary> /// 二维码 /// </summary> public byte[] QRStream { get; set; } public ExportWordData() { Title = ""; CTitle = ""; Remark = ""; Phone = ""; QRStream = null; } } #endregion }
{ "wordstyle ": [ { "wtype ": 1, "pagewidth ": 21, "pageheight ": 29.7, "topmargin ": 0.9, "bottommargin ": 0.5, "leftmargin ": 1.2, "rightmargin ": 1, "tableset ": { "rownum ": 6, "colnum ": 5, "fontfamily ": "宋体 ", "fontsize ": 12, "textposition": 5, "hborderval ": 5, "hbordercolor ": "gray ", "vborderval ": 5, "vbordercolor ": "gray ", "tborderval ": 5, "tbordercolor ": "gray ", "bborderval ": 5, "bbordercolor ": "gray ", "lborderval ": 5, "lbordercolor ": "gray ", "rborderval ": 5, "rbordercolor ": "gray ", "qrcodepos ": 1, "imgwidth ": 4.15, "imgheight ": 4.15, "paragraphstyle ": [ { "paragraphindex ": 1, "fontfamily ": "宋体 ", "fontsize ": 12, "fontcolor ": "", "isbold ": true }, { "paragraphindex ": 2, "fontfamily ": "宋体 ", "fontsize ": 12, "fontcolor ": "", "isbold ": true } ] } }, { "wtype ": 2, "pagewidth ": 29.7, "pageheight ": 21, "topmargin ": 1.5, "bottommargin ": 1.2, "leftmargin ": 1.5, "rightmargin ": 1.5, "tableset ": { "rownum ": 2, "colnum ": 5, "fontfamily ": "宋体 ", "fontsize ": 12, "textposition": 20, "hborderval ": 5, "hbordercolor ": "gray ", "vborderval ": 5, "vbordercolor ": "gray ", "tborderval ": 5, "tbordercolor ": "gray ", "bborderval ": 5, "bbordercolor ": "gray ", "lborderval ": 5, "lbordercolor ": "gray ", "rborderval ": 5, "rbordercolor ": "gray ", "qrcodepos ": 1, "imgwidth ": 8, "imgheight ": 8, "paragraphstyle ": [ { "paragraphindex ": 1, "fontfamily ": "宋体 ", "fontsize ": 12, "fontcolor ": "", "isbold ": true }, { "paragraphindex ": 2, "fontfamily ": "宋体 ", "fontsize ": 12, "fontcolor ": "", "isbold ": true } ] } }, { "wtype ": 3, "pagewidth ": 29.7, "pageheight ": 21, "topmargin ": 1.5, "bottommargin ": 1.2, "leftmargin ": 1.5, "rightmargin ": 1.5, "tableset ": { "rownum ": 2, "colnum ": 5, "fontfamily ": "宋体 ", "fontsize ": 12, "textposition": 20, "hborderval ": 5, "hbordercolor ": "gray ", "vborderval ": 5, "vbordercolor ": "gray ", "tborderval ": 5, "tbordercolor ": "gray ", "bborderval ": 5, "bbordercolor ": "gray ", "lborderval ": 5, "lbordercolor ": "gray ", "rborderval ": 5, "rbordercolor ": "gray ", "qrcodepos ": 0, "imgwidth ": 8, "imgheight ": 8, "paragraphstyle ": [ { "paragraphindex ": 1, "fontfamily ": "宋体 ", "fontsize ": 12, "fontcolor ": "", "isbold ": true }, { "paragraphindex ": 2, "fontfamily ": "宋体 ", "fontsize ": 12, "fontcolor ": "", "isbold ": true } ] } }, { "wtype ": 4, "pagewidth ": 14, "pageheight ": 8.5, "topmargin ": 0.75, "bottommargin ": 0.75, "leftmargin ": 0.75, "rightmargin ": 0.75, "tableset ": { "rownum ": 1, "colnum ": 2, "fontfamily ": "宋体 ", "fontsize ": 12, "textposition": 20, "hborderval ": 5, "hbordercolor ": "gray ", "vborderval ": 5, "vbordercolor ": "gray ", "tborderval ": 5, "tbordercolor ": "gray ", "bborderval ": 5, "bbordercolor ": "gray ", "lborderval ": 5, "lbordercolor ": "gray ", "rborderval ": 5, "rbordercolor ": "gray ", "qrcodepos ": 0, "imgwidth ": 7.01, "imgheight ": 7.01, "paragraphstyle ": [ { "paragraphindex ":1, "fontfamily ": "宋体 ", "fontsize ": 12, "fontcolor ": "", "isbold ": true }, { "paragraphindex ":2, "fontfamily ": "宋体 ", "fontsize ": 12, "fontcolor ": "", "isbold ": true } ] } }, { "wtype ": 5, "pagewidth ": 14, "pageheight ": 8.5, "topmargin ": 0.75, "bottommargin ": 0.75, "leftmargin ": 0.75, "rightmargin ": 0.75, "tableset ": { "rownum ": 1, "colnum ": 2, "fontfamily ": "宋体 ", "fontsize ": 12, "textposition": 20, "hborderval ": 5, "hbordercolor ": "gray ", "vborderval ": 5, "vbordercolor ": "gray ", "tborderval ": 5, "tbordercolor ": "gray ", "bborderval ": 5, "bbordercolor ": "gray ", "lborderval ": 5, "lbordercolor ": "gray ", "rborderval ": 5, "rbordercolor ": "gray ", "qrcodepos ": 1, "imgwidth ": 7.01, "imgheight ": 7.01, "paragraphstyle ": [ { "paragraphindex ": 1, "fontfamily ": "宋体 ", "fontsize ": 12, "fontcolor ": "", "isbold ": true }, { "paragraphindex ": 2, "fontfamily ": "宋体 ", "fontsize ": 12, "fontcolor ": "", "isbold ": true } ] } }, { "wtype ": 6, "pagewidth ": 10, "pageheight ": 5, "topmargin ": 0.4, "bottommargin ": 0.3, "leftmargin ": 0.5, "rightmargin ": 0.5, "tableset ": { "rownum ": 1, "colnum ": 2, "fontfamily ": "宋体 ", "fontsize ": 9, "textposition": 10, "hborderval ": 5, "hbordercolor ": "gray ", "vborderval ": 5, "vbordercolor ": "gray ", "tborderval ": 5, "tbordercolor ": "gray ", "bborderval ": 5, "bbordercolor ": "gray ", "lborderval ": 5, "lbordercolor ": "gray ", "rborderval ": 5, "rbordercolor ": "gray ", "qrcodepos ": 0, "imgwidth ": 4, "imgheight ": 4, "paragraphstyle ": [ { "paragraphindex ":1, "fontfamily ": "宋体 ", "fontsize ":9, "fontcolor ": "", "isbold ": true }, { "paragraphindex ": 2, "fontfamily ": "宋体 ", "fontsize ": 9, "fontcolor ": "", "isbold ": true } ] } }, { "wtype ": 7, "pagewidth ": 10, "pageheight ": 5, "topmargin ": 0.4, "bottommargin ": 0.3, "leftmargin ": 0.5, "rightmargin ": 0.5, "tableset ": { "rownum ": 1, "colnum ": 2, "fontfamily ": "宋体 ", "fontsize ": 9, "textposition": 10, "hborderval ": 5, "hbordercolor ": "gray ", "vborderval ": 5, "vbordercolor ": "gray ", "tborderval ": 5, "tbordercolor ": "gray ", "bborderval ": 5, "bbordercolor ": "gray ", "lborderval ": 5, "lbordercolor ": "gray ", "rborderval ": 5, "rbordercolor ": "gray ", "qrcodepos ": 1, "imgwidth ": 4, "imgheight ": 4, "paragraphstyle ": [ { "paragraphindex ": 1, "fontfamily ": "宋体 ", "fontsize ": 9, "fontcolor ": "", "isbold ": true }, { "paragraphindex ": 2, "fontfamily ": "宋体 ", "fontsize ": 9, "fontcolor ": "", "isbold ": true } ] } }, { "wtype ": 8, "pagewidth ": 6, "pageheight ": 3, "topmargin ": 0.1, "bottommargin ": 0.1, "leftmargin ": 0.1, "rightmargin ": 0.1, "tableset ": { "rownum ": 1, "colnum ": 2, "fontfamily ": "宋体", "fontsize ":6.5, "textposition":5, "hborderval ": 5, "hbordercolor ": "gray ", "vborderval ": 5, "vbordercolor ": "gray ", "tborderval ": 5, "tbordercolor ": "gray ", "bborderval ": 5, "bbordercolor ": "gray ", "lborderval ": 5, "lbordercolor ": "gray ", "rborderval ": 5, "rbordercolor ": "gray ", "qrcodepos ": 0, "imgwidth ": 2.72, "imgheight ": 2.72, "paragraphstyle ": [ { "paragraphindex ": 1, "fontfamily ": "宋体 ", "fontsize ":6.5, "fontcolor ": "", "isbold ": true }, { "paragraphindex ":2, "fontfamily ": "宋体 ", "fontsize ": 6.5, "fontcolor ": "", "isbold ": true } ] } }, { "wtype ": 9, "pagewidth ": 4, "pageheight ": 3, "topmargin ": 0.1, "bottommargin ": 0.1, "leftmargin ": 0.1, "rightmargin ": 0.1, "tableset ": { "rownum ": 1, "colnum ": 2, "fontfamily ": "宋体 ", "fontsize ":5, "textposition":5, "hborderval ": 5, "hbordercolor ": "gray ", "vborderval ": 5, "vbordercolor ": "gray ", "tborderval ": 5, "tbordercolor ": "gray ", "bborderval ": 5, "bbordercolor ": "gray ", "lborderval ": 5, "lbordercolor ": "gray ", "rborderval ": 5, "rbordercolor ": "gray ", "qrcodepos ": 0, "imgwidth ": 2.49, "imgheight ": 2.49, "paragraphstyle ": [ { "paragraphindex ": 1, "fontfamily ": "宋体 ", "fontsize ": 5, "fontcolor ": "", "isbold ": true }, { "paragraphindex ": 2, "fontfamily ": "宋体 ", "fontsize ":5, "fontcolor ": "", "isbold ": true } ] } }, { "wtype ": 10, "pagewidth ": 10, "pageheight ": 5, "topmargin ": 0.4, "bottommargin ": 0.3, "leftmargin ": 0.5, "rightmargin ": 0.5, "tableset ": { "rownum ": 1, "colnum ": 2, "fontfamily ": "宋体 ", "fontsize ":9, "textposition":10, "hborderval ": 5, "hbordercolor ": "gray ", "vborderval ": 5, "vbordercolor ": "gray ", "tborderval ": 5, "tbordercolor ": "gray ", "bborderval ": 5, "bbordercolor ": "gray ", "lborderval ": 5, "lbordercolor ": "gray ", "rborderval ": 5, "rbordercolor ": "gray ", "qrcodepos ": 0, "imgwidth ": 4, "imgheight ": 4, "paragraphstyle ": [ { "paragraphindex ": 1, "fontfamily ": "宋体 ", "fontsize ": 9, "fontcolor ": "", "isbold ": true }, { "paragraphindex ": 2, "fontfamily ": "宋体 ", "fontsize ":9, "fontcolor ": "", "isbold ": true } ] } } ] }
实现10中导出word效果
模板资源:(12条消息) C#Word导出之NPOI-10个模板-C#文档类资源-CSDN文库
本文来自博客园,作者:じ逐梦,转载请注明原文链接:https://www.cnblogs.com/ZhuMeng-Chao/p/17074271.html