C#使用NPOI进行word的读写(项目案例)
/// <summary> /// 导出记录 /// </summary> /// <returns></returns> public async Task<ActionResult> DownloadRecord() { //数据源 var model = new PracticalRecordModel(); // 方法 var doc = EquipWordHelper.ExportPracticalRecordReceipt(model); using (MemoryStream ms = new MemoryStream()) { doc.Write(ms); // 文件名 string fileName = $"{DateTime.Now.ToString("yyyy-MM-dd")}.docx"; return File(ms.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, fileName); } }
处理方法:ExportPracticalRecordReceipt
public static XWPFDocument ExportPracticalRecordReceipt(PracticalRecordModel model, int type = 1) { var template = Folder + "PracticalRecord.docx"; using (FileStream stream = new FileStream(template, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { XWPFDocument doc = new XWPFDocument(stream); // 注意-模板的标题要和这里一样,模板的括号是英文的 doc.Tables[0].Rows[0].GetTableCells()[0].Paragraphs[0].Runs[0].ReplaceText("[标题]", "项目" + model.JobName + "实操考核记录"); doc.Tables[0].Rows[1].GetTableCells()[1].Paragraphs[0].Runs[0].ReplaceText("[总包单位]", model.OrgName); doc.Tables[0].Rows[1].GetTableCells()[3].Paragraphs[0].Runs[0].ReplaceText("[考核人员]", model.KhName); doc.Tables[0].Rows[1].GetTableCells()[5].Paragraphs[0].Runs[0].ReplaceText("[面试日期]", model.InterviewTimeStr); doc.Tables[0].Rows[2].GetTableCells()[1].Paragraphs[0].Runs[0].ReplaceText("[分包单位]", model.ProjectName); doc.Tables[0].Rows[2].GetTableCells()[3].Paragraphs[0].Runs[0].ReplaceText("[实操人员]", model.ScName); doc.Tables[0].Rows[2].GetTableCells()[5].Paragraphs[0].Runs[0].ReplaceText("[考核工种]", model.JobName); int RowsIndex = 5; ExportPracticalRecordListReceiptFill(model, ref doc, ref RowsIndex); foreach (var image in model.AssessMentPaths) { XWPFParagraph par = doc.Tables[0].Rows[RowsIndex].GetTableCells()[0].Paragraphs[0]; XWPFRun run = par.CreateRun(); byte[] byData = GetBytesFromUrl(image); using (MemoryStream ms = new MemoryStream(byData)) { run.AddPicture(ms, (int)PictureType.JPEG, "10.jpg", (int)(500.0 * 9525), (int)(400.0 * 9525)); } } var restr = ""; doc.Tables[0].Rows[RowsIndex + 1].GetTableCells()[0].Paragraphs[1].Runs[0].ReplaceText("[实操考核结论]", restr); return doc; } } /// <summary>
/// 处理动态数据 /// </summary> /// <param name="model"></param> /// <param name="doc"></param> /// <param name="RowsIndex"></param> public static void ExportPracticalRecordListReceiptFill(PracticalRecordModel model, ref XWPFDocument doc, ref int RowsIndex) { var list = model.PracticalRecordDetailList.OrderBy(x => x.Sort).ToList(); var sort = 1; foreach (var item in list) { if (RowsIndex != 5) { CT_Row m_NewRow = new CT_Row(); var MyRow = new XWPFTableRow(m_NewRow, doc.Tables[0]); // 添加行--AddRow 有2种用法,下面使用的是在文档中间插入,doc.Tables[0].AddRow(Myrow);这种是默认在文档末尾添加 doc.Tables[0].AddRow(MyRow, RowsIndex); var cell = MyRow.CreateCell(); var cttc = cell.GetCTTc(); var cp = cttc.AddNewTcPr(); //添加列 cp.gridSpan = new CT_DecimalNumber(); cell = MyRow.CreateCell(); cttc = cell.GetCTTc(); cp = cttc.AddNewTcPr(); cp.gridSpan = new CT_DecimalNumber(); cell = MyRow.CreateCell(); cttc = cell.GetCTTc(); cp = cttc.AddNewTcPr(); cp.gridSpan = new CT_DecimalNumber(); cp.gridSpan.val = "3"; //合并列 cell = MyRow.CreateCell(); cttc = cell.GetCTTc(); cp = cttc.AddNewTcPr(); cp.gridSpan = new CT_DecimalNumber(); cell = MyRow.CreateCell(); cttc = cell.GetCTTc(); cp = cttc.AddNewTcPr(); cp.gridSpan = new CT_DecimalNumber();
#region 第一行(这种添加行是,要复制对应行的样式,在进行添加行,上面是自行设定合并行,大部分按照这种方式执行即可) // 获取 Word 文档中的第一个表格 XWPFTable table = doc.Tables[0]; // 开始补行数了 CT_Row ctrow = table.Rows[RowsIndex].GetCTRow(); //找模板 //tables[0].RemoveRow(12); //先移除模板行 CT_Row targetRow = new CT_Row(); // 复制cell结构 foreach (CT_Tc itemtc in ctrow.Items) { CT_Tc addTc = targetRow.AddNewTc(); addTc.tcPr = itemtc.tcPr;//cell样式,只包括列宽和cell对齐方式 IList<CT_P> list_p = itemtc.GetPList(); foreach (var p in list_p) { CT_P addP = addTc.AddNewP(); addP.pPr = p.pPr;//段落样式 IList<CT_R> list_r = p.GetRList(); foreach (CT_R r in list_r) { CT_R addR = addP.AddNewR(); addR.rPr = r.rPr;//run样式 包括字体等 List<CT_Text> list_text = r.GetTList(); foreach (CT_Text text in list_text) { CT_Text addText = addR.AddNewT(); addText.space = text.space; addText.Value = text.Value; } } } } //增加数据行 XWPFTableRow mrow = new XWPFTableRow(targetRow, table); table.AddRow(mrow, RowsIndex); #endregion
} //序号 XWPFParagraph para = doc.Tables[0].Rows[RowsIndex].GetTableCells()[0].Paragraphs[0]; para.Alignment = ParagraphAlignment.CENTER; XWPFRun run = para.CreateRun(); run.SetText(sort.ToString()); run.IsBold = true; sort++; // 考核项目 para = doc.Tables[0].Rows[RowsIndex].GetTableCells()[1].Paragraphs[0]; para.Alignment = ParagraphAlignment.CENTER; run = para.CreateRun(); run.SetText(item.ExamProject); run.IsBold = true; // 考核标准 para = doc.Tables[0].Rows[RowsIndex].GetTableCells()[2].Paragraphs[0]; para.Alignment = ParagraphAlignment.CENTER; run = para.CreateRun(); run.SetText(item.ExamStandard); run.IsBold = true; // 结论-合格 para = doc.Tables[0].Rows[RowsIndex].GetTableCells()[3].Paragraphs[0]; para.Alignment = ParagraphAlignment.CENTER; run = para.CreateRun(); run.SetText(item.IsQualified == 0 ? "√" : ""); run.IsBold = true; // 结论-不合格 para = doc.Tables[0].Rows[RowsIndex].GetTableCells()[4].Paragraphs[0]; para.Alignment = ParagraphAlignment.CENTER; run = para.CreateRun(); run.SetText(item.IsQualified == 1 ? "√" : ""); run.IsBold = true; RowsIndex++; } }
// 一行设置2种字体样式--案例--和上面的代码面关联 XWPFParagraph para = doc.Tables[0].Rows[RowsIndex].GetTableCells()[0].Paragraphs[0]; para.Alignment = ParagraphAlignment.LEFT; XWPFRun run = para.CreateRun(); var pointname = sort.ToString("D2") + "-" + item.PointName + ":"; run.SetText(pointname); run.IsBold = true; run.FontSize = 14; run.SetFontFamily("仿宋_GB2312", FontCharRange.None); // 添加换行符 para.CreateRun().AddCarriageReturn(); // 创建文本2,并设置其样式 XWPFRun run2 = para.CreateRun(); run2.SetText(item.Remark); run2.FontFamily = "仿宋_GB2312"; run2.FontSize = 10;
文件模板
导出结果