网上找了好多文章都没有准确的操作word表格换行的操作,参考网上文章摸索了一天的成果记录一下。
一、word表格,注意要设置表格高度自动
二、代码
public static void CreateWoedFile() { try { string temp_path = AppDomain.CurrentDomain.BaseDirectory + @"Files\Temp\{0}\".Ft(DateTime.Now.ToString("yyyyMMdd"));//临时文件路径 var file_name2 = $"{DateTime.Now.ToString("yyyyMMddhhmmss")}.docx";//文件名称转换生成 var Temp_url = @"C:\Users\Administrator\Desktop\test.docx"; Stream workstream = System.IO.File.OpenRead(Temp_url); XWPFDocument workdoctemp = new XWPFDocument(workstream); int iRow = 0;//表中行的循环索引 int iCell = 0;//表中列的循环索引 var IndexNoList = new List<string>() { "1", "2", "3", "4" }; var NameList = new List<string>() { "张三", "李四", "小明", "小红" }; var DateList = new List<string>() { "2022/02/03", "2022/02/03", "2022/02/03", "2022/02/03" }; foreach (var table in workdoctemp.Tables) { //2.循环表格行 foreach (XWPFTableRow row in table.Rows) { iRow = table.Rows.IndexOf(row);//获取该循环在List集合中的索引 foreach (XWPFTableCell cell in row.GetTableCells()) { iCell = row.GetTableCells().IndexOf(cell);//获取该循环在List集合中的索引 IList<XWPFParagraph> listXWPFParagraph = cell.Paragraphs; string mark = string.Empty; foreach (var para in listXWPFParagraph) { //这里不能操作Cell不然会报错 if (para.ParagraphText.IndexOf("index_no") >= 0) { mark = "index_no"; } if (para.ParagraphText.IndexOf("name") >= 0) { mark = "name"; } if (para.ParagraphText.IndexOf("date") >= 0) { mark = "date"; } } switch (mark) { case "index_no": cell.RemoveParagraph(0);//删掉原有的内容 IndexNoList.ForEach(x => { var newcell = cell.AddParagraph();//创建一行 //newcell.Alignment = ParagraphAlignment.CENTER;//文字剧中 var newrun = newcell.CreateRun();//创建一个集合 newrun.SetText("\n\r" + x);//设置内容 newrun.FontSize = 10; var count = cell.Paragraphs.Count; cell.Paragraphs[count - 1].AddRun(newrun); }); break; case "name": cell.RemoveParagraph(0);//删掉原有的内容 NameList.ForEach(x => { var newcell = cell.AddParagraph();//创建一行 //newcell.Alignment = ParagraphAlignment.CENTER;//文字剧中 var newrun = newcell.CreateRun();//创建一个集合 newrun.SetText("\n\r" + x); newrun.FontSize = 10; var count = cell.Paragraphs.Count; cell.Paragraphs[count - 1].AddRun(newrun); }); break; case "date": cell.RemoveParagraph(0);//删掉原有的内容 DateList.ForEach(x => { var newcell = cell.AddParagraph();//创建一行 //newcell.Alignment = ParagraphAlignment.CENTER;//文字剧中 var newrun = newcell.CreateRun();//创建一个集合 newrun.SetText("\n\r" + x); newrun.FontSize = 10; var count = cell.Paragraphs.Count; cell.Paragraphs[count - 1].AddRun(newrun); }); break; } } } } if (!Directory.Exists(temp_path)) Directory.CreateDirectory(temp_path); using (FileStream fileSave = new FileStream(temp_path + file_name2, FileMode.Create, FileAccess.Write)) { workdoctemp.Write(fileSave); } } catch (Exception ex) { } }
三、效果