poi导出WORD表格居中
JavaPOI操作word文档内容、表格
JavaPOI操作word⽂档内容、表格⼀、pom<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.0.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.0.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.0.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.0.0</version></dependency>⼆、直接上代码word模板中${content} 注意我只有在.docx⽤XWPFDocument才有效2.1/*** 获取document**/XWPFDocument document = null;try {document = new XWPFDocument(inputStream);} catch (IOException ioException) {ioException.printStackTrace();}/*** 替换段落⾥⾯的变量** @param doc 要替换的⽂档* @param params 参数*/private void replaceInPara(XWPFDocument doc, Map<String, String> params) {for (XWPFParagraph para : doc.getParagraphs()) {replaceInPara(para, params);}}/*** 替换段落⾥⾯的变量** @param para 要替换的段落* @param params 参数*/private void replaceInPara(XWPFParagraph para, Map<String, String> params) {List<XWPFRun> runs;Matcher matcher;replaceText(para);//如果para拆分的不对,则⽤这个⽅法修改成正确的if (matcher(para.getParagraphText()).find()) {runs = para.getRuns();for (int i = 0; i < runs.size(); i++) {XWPFRun run = runs.get(i);String runText = run.toString();matcher = matcher(runText);if (matcher.find()) {while ((matcher = matcher(runText)).find()) {runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));}//直接调⽤XWPFRun的setText()⽅法设置⽂本时,在底层会重新创建⼀个XWPFRun,把⽂本附加在当前⽂本后⾯, para.removeRun(i);para.insertNewRun(i).setText(runText);}}}}/*** 替换⽂本内容* @param para* @return*/private List<XWPFRun> replaceText(XWPFParagraph para) {List<XWPFRun> runs = para.getRuns();String str = "";boolean flag = false;for (int i = 0; i < runs.size(); i++) {XWPFRun run = runs.get(i);String runText = run.toString();if (flag || runText.equals("${")) {str = str + runText;flag = true;para.removeRun(i);if (runText.equals("}")) {flag = false;para.insertNewRun(i).setText(str);str = "";}i--;}}return runs;}2.22.2.1XWPFTable table = document.getTableArray(0);//获取当前表格XWPFTableRow twoRow = table.getRow(2);//获取某⼀⾏XWPFTableRow nextRow = table.insertNewTableRow(3);//插⼊⼀⾏XWPFTableCell firstRowCellOne = firstRow.getCell(0);firstRowCellOne.removeParagraph(0);//删除默认段落,要不然表格内第⼀条为空⾏XWPFParagraph pIO2 =firstRowCellOne.addParagraph();XWPFRun rIO2 = pIO2.createRun();rIO2.setFontFamily("宋体");//字体rIO2.setFontSize(8);//字体⼤⼩rIO2.setBold(true);//是否加粗rIO2.setColor("FF0000");//字体颜⾊rIO2.setText("这是写⼊的内容");//rIO2.addBreak(BreakType.TEXT_WRAPPING);//软换⾏,亲测有效/*** 复制单元格和样式** @param targetRow 要复制的⾏* @param sourceRow 被复制的⾏*/public void createCellsAndCopyStyles(XWPFTableRow targetRow, XWPFTableRow sourceRow) {targetRow.getCtRow().setTrPr(sourceRow.getCtRow().getTrPr());List<XWPFTableCell> tableCells = sourceRow.getTableCells();if (CollectionUtils.isEmpty(tableCells)) {return;}for (XWPFTableCell sourceCell : tableCells) {XWPFTableCell newCell = targetRow.addNewTableCell();newCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());List sourceParagraphs = sourceCell.getParagraphs();if (CollectionUtils.isEmpty(sourceParagraphs)) {continue;}XWPFParagraph sourceParagraph = (XWPFParagraph) sourceParagraphs.get(0);List targetParagraphs = newCell.getParagraphs();if (CollectionUtils.isEmpty(targetParagraphs)) {XWPFParagraph p = newCell.addParagraph();p.getCTP().setPPr(sourceParagraph.getCTP().getPPr());XWPFRun run = p.getRuns().isEmpty() ? p.createRun() : p.getRuns().get(0);run.setFontFamily(sourceParagraph.getRuns().get(0).getFontFamily());} else {XWPFParagraph p = (XWPFParagraph) targetParagraphs.get(0);p.getCTP().setPPr(sourceParagraph.getCTP().getPPr());XWPFRun run = p.getRuns().isEmpty() ? p.createRun() : p.getRuns().get(0);if (sourceParagraph.getRuns().size() > 0) {run.setFontFamily(sourceParagraph.getRuns().get(0).getFontFamily());}}}}#### 2.2.3/*** 合并单元格** @param table 表格对象* @param beginRowIndex 开始⾏索引* @param endRowIndex 结束⾏索引* @param colIndex 合并列索引*/public void mergeCell(XWPFTable table, int beginRowIndex, int endRowIndex, int colIndex) { if (beginRowIndex == endRowIndex || beginRowIndex > endRowIndex) {return;}//合并⾏单元格的第⼀个单元格CTVMerge startMerge = CTVMerge.Factory.newInstance();startMerge.setVal(STMerge.RESTART);//合并⾏单元格的第⼀个单元格之后的单元格CTVMerge endMerge = CTVMerge.Factory.newInstance();endMerge.setVal(STMerge.CONTINUE);table.getRow(beginRowIndex).getCell(colIndex).getCTTc().getTcPr().setVMerge(startMerge); for (int i = beginRowIndex + 1; i <= endRowIndex; i++) {table.getRow(i).getCell(colIndex).getCTTc().getTcPr().setVMerge(endMerge);}}/*** insertRow 在word表格中指定位置插⼊⼀⾏,并将某⼀⾏的样式复制到新增⾏* @param copyrowIndex 需要复制的⾏位置* @param newrowIndex 需要新增⼀⾏的位置* */public static void insertRow(XWPFTable table, int copyrowIndex, int newrowIndex) {// 在表格中指定的位置新增⼀⾏XWPFTableRow targetRow = table.insertNewTableRow(newrowIndex);// 获取需要复制⾏对象XWPFTableRow copyRow = table.getRow(copyrowIndex);//复制⾏对象targetRow.getCtRow().setTrPr(copyRow.getCtRow().getTrPr());//或许需要复制的⾏的列List<XWPFTableCell> copyCells = copyRow.getTableCells();//复制列对象XWPFTableCell targetCell = null;for (int i = 0; i < copyCells.size(); i++) {XWPFTableCell copyCell = copyCells.get(i);targetCell = targetRow.addNewTableCell();targetCell.getCTTc().setTcPr(copyCell.getCTTc().getTcPr());if (copyCell.getParagraphs() != null && copyCell.getParagraphs().size() > 0) {targetCell.getParagraphs().get(0).getCTP().setPPr(copyCell.getParagraphs().get(0).getCTP().getPPr()); if (copyCell.getParagraphs().get(0).getRuns() != null&& copyCell.getParagraphs().get(0).getRuns().size() > 0) {XWPFRun cellR = targetCell.getParagraphs().get(0).createRun();cellR.setBold(copyCell.getParagraphs().get(0).getRuns().get(0).isBold());}}}}/*** 正则匹配字符串** @param str* @return*/private Matcher matcher(String str) {Pattern pattern = pile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);Matcher matcher = pattern.matcher(str);return matcher;}。
文件导入导出Word、Excel
第三方jar简介1. POI 简介POI 是Apache 下的Jakata 项目的一个子项目,主要用于提供java 操作MicrosoftOffice 办公套件如Excel,Word,Powerpoint 等文件的API.微软的Office 办公软件在企业的日常办公中占据着重要的地位,人们已经非常熟悉Office 的使用。
在我们开发的应用系统中,常常需要将数据导出到Excel 文件中,或者Word 文件中进行打印。
比如移动的话费查询系统中就提供了将话费清单导入到excel 表格中的功能。
这样在web 应用中,我们在浏览器中看到的数据可以被导出到Excel 中了。
Excel 文件: xls 格式文件对应POI API 为HSSF 。
xlsx 格式为office 2007 的文件格式,POI 中对应的API 为XSSFWord 文件:doc 格式文件对应的POI API 为HWPF。
docx 格式为XWPF powerPoint 文件:ppt 格式对应的POI API 为HSLF。
pptx 格式为XSLFoutlook :对应的API 为HSMFVisio: 对应的API 为HDGFPublisher : 对应的API 为HPBF2. iText简介iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java 类库。
通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。
iText的安装非常方便,下载iText.jar文件后,只需要在系统的CLASSPATH 中加入iText.jar的路径,在程序中就可以使用iText类库了。
用处一般情况下,iText使用在有以下一个要求的项目中:∙内容无法提前利用:取决于用户的输入或实时的数据库信息。
∙由于内容,页面过多,PDF文档不能手动生成。
∙文档需在无人参与,批处理模式下自动创建。
POI详细教程范文
POI详细教程范文POI是一种非常常用的Java库,用于处理各种办公软件文件的读写操作。
它提供了丰富的API,可以操作Microsoft Excel、Word和PowerPoint等文件格式。
本文将介绍POI的基本概念和使用方法,以及一些常见应用场景。
一、POI的概念和基本使用方法1.POI的概念POI全称为Apache POI,是Apache软件基金会下的一个开源项目。
它提供了Java实现的Microsoft Office文件格式读写功能。
通过POI,我们可以读取和写入Excel、Word和PowerPoint等文件,实现数据的导入和导出、模板的生成等功能。
2.POI的引入首先,在Maven项目中引入POI的依赖:```<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency>```3. Excel文件的读写操作(1)创建工作簿和工作表首先,我们需要创建一个工作簿对象,代表整个Excel文件:```Workbook workbook = new XSSFWorkbook(; // 创建一个新的工作簿```然后,创建一个工作表对象,代表Excel中的一个表格:```Sheet sheet = workbook.createSheet("Sheet1"); // 创建一个新的工作表```(2)添加数据到单元格接下来,我们可以向工作表中的单元格添加数据。
指定单元格所在的行和列,然后设置相应的值:```Row row = sheet.createRow(0); // 创建第一行Cell cell = row.createCell(0); // 创建第一列cell.setCellValue("Hello, World!"); // 设置单元格的值```(3) 保存Excel文件最后,我们需要将工作簿保存为一个Excel文件:```FileOutputStream fileOut = newFileOutputStream("workbook.xlsx"); // 创建输出流workbook.write(fileOut); // 写入文件fileOut.close(; // 关闭输出流workbook.close(; // 关闭工作簿```4. Word文件的读写操作(1)创建文档对象首先,我们需要创建一个文档对象,代表整个Word文件:```XWPFDocument document = new XWPFDocument(; // 创建一个新的文档```(2)添加段落和文本接下来,我们可以向文档中添加段落和文本。
javapoi实现word导出(包括word模板的使用、复制表格、复制行、插入图片的使用)
/** * 功能描述:word下载 * * @param response * @param patientMap * @param list * @param itemList * @param file * @see [相关类/方法](可选) * @since [产品/模块版本](可选) */ public static final void DownloadWord(HttpServletResponse response, Map<String, Object> patientMap, List<Map<String, Object>> list, List<List<String>> itemList, String file) {
博客园 用户登录 代码改变世界 密码登录 短信登录 忘记登录用户名 忘记密码 记住我 登录 第三方登录/注册 没有账户, 立即注册
javapoi实现 word导出(包括 word模板的使用、复制表格、复制 行、插入图片的使用)
java poi实现数据的word导出(包括word模板的使用、复制表格、复制行、插入图片的使用) 1.实现的效果 实现病人基本信息、多条病历数据、多项检查项图片的动态插入(网络图片)
/** * 功能描述:复制段落,从source到target * * @param target * @param source * @param index * @see [相关类/方法](可选) * @since [产品/模块版本](可选) */ public static void copyParagraph(XWPFParagraph target, XWPFParagraph source, Integer index) { // 设置段落样式 target.getCTP().setPPr(source.getCTP().getPPr()); // 移除所有的run for (int pos = target.getRuns().size() - 1; pos >= 0; pos--) { target.removeRun(pos); } // copy 新的run for (XWPFRun s : source.getRuns()) { XWPFRun targetrun = target.createRun(); copyRun(targetrun, s, index); } }
javaPOI单元格格式设置居中
javaPOI单元格格式设置居中设置颜⾊,设置前景⾊style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());style.setFillPattern(FillPatternType.SOLID_FOREGROUND);设置居中对齐//设置⽔平对齐的样式为居中对齐;style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置垂直对齐的样式为居中对齐;style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);⾃适应宽度//⾃动设置⾏⾼int colLength = cell.getStringCellValue().getBytes().length*256; //sheet.setColumnWidth(col, colLength);package mon;import java.io.IOException;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletResponse;import ermodel.HSSFCell;import ermodel.HSSFCellStyle;import ermodel.HSSFFont;import ermodel.HSSFRichTextString;import ermodel.HSSFRow;import ermodel.HSSFSheet;import ermodel.HSSFWorkbook;import org.apache.poi.hssf.util.CellRangeAddress;import org.apache.poi.hssf.util.HSSFColor;/*** 导出Excel公共⽅法* @version 1.0** @author wangcp**/public class ExportExcel extends BaseAction {//显⽰的导出表的标题private String title;//导出表的列名private String[] rowName ;private List<Object[]> dataList = new ArrayList<Object[]>();HttpServletResponse response;//构造⽅法,传⼊要导出的数据public ExportExcel(String title,String[] rowName,List<Object[]> dataList){this.dataList = dataList;this.rowName = rowName;this.title = title;}/** 导出数据* */public void export() throws Exception{try{HSSFWorkbook workbook = new HSSFWorkbook(); // 创建⼯作簿对象HSSFSheet sheet = workbook.createSheet(title); // 创建⼯作表// 产⽣表格标题⾏HSSFRow rowm = sheet.createRow(0);HSSFCell cellTiltle = rowm.createCell(0);//sheet样式定义【getColumnTopStyle()/getStyle()均为⾃定义⽅法 - 在下⾯ - 可扩展】HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));cellTiltle.setCellStyle(columnTopStyle);cellTiltle.setCellValue(title);// 定义所需列数int columnNum = rowName.length;HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建⾏(最顶端的⾏开始的第⼆⾏) // 将列头设置到sheet的单元格中for(int n=0;n<columnNum;n++){HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型HSSFRichTextString text = new HSSFRichTextString(rowName[n]);cellRowName.setCellValue(text); //设置列头单元格的值cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式}//将查询出的数据设置到sheet对应的单元格中for(int i=0;i<dataList.size();i++){Object[] obj = dataList.get(i);//遍历每个对象HSSFRow row = sheet.createRow(i+3);//创建所需的⾏数for(int j=0; j<obj.length; j++){HSSFCell cell = null; //设置单元格的数据类型if(j == 0){cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);cell.setCellValue(i+1);}else{cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);if(!"".equals(obj[j]) && obj[j] != null){cell.setCellValue(obj[j].toString()); //设置单元格的值}}cell.setCellStyle(style); //设置单元格样式}}//让列宽随着导出的列长⾃动适应for (int colNum = 0; colNum < columnNum; colNum++) {int columnWidth = sheet.getColumnWidth(colNum) / 256;for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {HSSFRow currentRow;//当前⾏未被使⽤过if (sheet.getRow(rowNum) == null) {currentRow = sheet.createRow(rowNum);} else {currentRow = sheet.getRow(rowNum);}if (currentRow.getCell(colNum) != null) {HSSFCell currentCell = currentRow.getCell(colNum);if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {int length = currentCell.getStringCellValue().getBytes().length;if (columnWidth < length) {columnWidth = length;}}}}if(colNum == 0){sheet.setColumnWidth(colNum, (columnWidth-2) * 256);}else{sheet.setColumnWidth(colNum, (columnWidth+4) * 256);}}if(workbook !=null){try{String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls"; String headStr = "attachment; filename=\"" + fileName + "\"";response = getResponse();response.setContentType("APPLICATION/OCTET-STREAM");response.setHeader("Content-Disposition", headStr);OutputStream out = response.getOutputStream();workbook.write(out);}catch (IOException e){e.printStackTrace();}}}catch(Exception e){e.printStackTrace();}}/** 列头单元格样式*/public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) { // 设置字体HSSFFont font = workbook.createFont();//设置字体⼤⼩font.setFontHeightInPoints((short)11);//字体加粗font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//设置字体名字font.setFontName("Courier New");//设置样式;HSSFCellStyle style = workbook.createCellStyle();//设置底边框;style.setBorderBottom(HSSFCellStyle.BORDER_THIN);//设置底边框颜⾊;style.setBottomBorderColor(HSSFColor.BLACK.index);//设置左边框;style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//设置左边框颜⾊;style.setLeftBorderColor(HSSFColor.BLACK.index);//设置右边框;style.setBorderRight(HSSFCellStyle.BORDER_THIN);//设置右边框颜⾊;style.setRightBorderColor(HSSFColor.BLACK.index);//设置顶边框;style.setBorderTop(HSSFCellStyle.BORDER_THIN);//设置顶边框颜⾊;style.setTopBorderColor(HSSFColor.BLACK.index);//在样式⽤应⽤设置的字体;style.setFont(font);//设置⾃动换⾏;style.setWrapText(false);//设置⽔平对齐的样式为居中对齐;style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置垂直对齐的样式为居中对齐;style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style;}/** 列数据信息单元格样式*/public HSSFCellStyle getStyle(HSSFWorkbook workbook) {// 设置字体HSSFFont font = workbook.createFont();//设置字体⼤⼩//font.setFontHeightInPoints((short)10);//字体加粗//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//设置字体名字font.setFontName("Courier New");//设置样式;HSSFCellStyle style = workbook.createCellStyle();//设置底边框;style.setBorderBottom(HSSFCellStyle.BORDER_THIN);//设置底边框颜⾊;style.setBottomBorderColor(HSSFColor.BLACK.index);//设置左边框;style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//设置左边框颜⾊;style.setLeftBorderColor(HSSFColor.BLACK.index);//设置右边框;style.setBorderRight(HSSFCellStyle.BORDER_THIN);//设置右边框颜⾊;style.setRightBorderColor(HSSFColor.BLACK.index);//设置顶边框;style.setBorderTop(HSSFCellStyle.BORDER_THIN);//设置顶边框颜⾊;style.setTopBorderColor(HSSFColor.BLACK.index);//在样式⽤应⽤设置的字体;style.setFont(font);//设置⾃动换⾏;style.setWrapText(false);//设置⽔平对齐的样式为居中对齐;style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置垂直对齐的样式为居中对齐;style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style;}}---------------------作者:艾伦蓝来源:CSDN原⽂:https:///lan12334321234/article/details/70049738 版权声明:本⽂为博主原创⽂章,转载请附上博⽂链接!。
Java使用Poi-tlword模板导出word
Java使⽤Poi-tlword模板导出word 1.导⼊依赖<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.7.3</version></dependency>2.新建⼀个word,制作导出模板模板放⼊ resource/static/word/template⽂件夹下3.编写⼯具类⼯具类--WordExportServer.javapublic class WordExportServer {/*** 导出word**/public static void export(WordExportData wordExportData) throws IOException {HttpServletResponse response=wordExportData.getResponse();OutputStream out = response.getOutputStream();;XWPFTemplate template =null;try{ClassPathResource classPathResource = new ClassPathResource(wordExportData.getTemplateDocPath());String resource = classPathResource.getURL().getPath();resource= PdfUtil1.handleFontPath(resource);//渲染表格HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();Configure config = Configure.newBuilder().bind(wordExportData.getTableDataField(), policy).build();template = pile(resource, config).render(wordExportData.getWordData());String fileName=getFileName(wordExportData);/** ===============⽣成word到设置浏览默认下载地址=============== **/// 设置强制下载不打开response.setContentType("application/force-download");// 设置⽂件名response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);template.write(out);}catch (Exception e){e.printStackTrace();}finally {out.flush();out.close();template.close();}}/*** 获取导出下载的word名称* @param wordExportData* @return ng.String**/public static String getFileName(WordExportData wordExportData){if(null !=wordExportData.getFileName()){return wordExportData.getFileName()+".docx";}return System.currentTimeMillis()+".docx";}}word数据包装类--WordExportData .java@Datapublic class WordExportData {/*** word模板路径(static/wordTemplate/dealerListDocTemplate.docx)**/private String templateDocPath;/*** word填充数据(key值与模板中的key值要保持⼀致)**/private Map<String,Object> wordData;/*** word表格数据key值**/private String tableDataField;/*** word导出后的⽂件名(不填则⽤当前时间代替)**/private String fileName;private HttpServletResponse response;}4.controller层调⽤@RequestMapping("/printWord")public void printWord(HttpServletRequest request, HttpServletResponse response) throws IOException{String[] ids=request.getParameter("ids").split(";");List<DealerDto> goodsDataList=goodsService.getDealerListByIds(ids);Map<String,Object> docData=new HashMap<>(3);docData.put("detailList",goodsDataList);docData.put("title",标题);docData.put("subTitle",副标题);WordExportData wordExportData=new WordExportData();wordExportData.setResponse(response);wordExportData.setTableDataField("detailList");wordExportData.setTemplateDocPath(DEALER_DOC_TEMPLATE_PATH);//副本存放路径wordExportData.setWordData(docData);WordExportServer.export(wordExportData);}5.前端调⽤var ids = [];for (var index in checkData) {ids.push(checkData[index].id);}var batchIds = ids.join(";");layer.confirm('确定下载选中的数据吗?', function (index) {layer.close(index);window.location.href ='/goods/printWord?ids=' + batchIds;});6.总结优点:使⽤⽅法很简单,使⽤⼯具类的⽅法,⽅便复⽤于其他模块。
javaPOI往word文档中指定位置插入表格
javaPOI往word⽂档中指定位置插⼊表格1.Service demoimport java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.math.BigInteger;import java.text.DecimalFormat;import java.text.NumberFormat;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Iterator;import java.util.List;import java.util.Map;import org.apache.poi.POIXMLDocument;import org.apache.poi.util.IOUtils;import ermodel.XWPFDocument;import ermodel.XWPFParagraph;import ermodel.XWPFRun;import ermodel.XWPFTable;import ermodel.XWPFTableCell;import ermodel.XWPFTableRow;import org.apache.xmlbeans.XmlCursor;import org.docx4j.TraversalUtil;import org.docx4j.dml.wordprocessingDrawing.Inline;import org.docx4j.finders.RangeFinder;import org.docx4j.openpackaging.packages.WordprocessingMLPackage;import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;import org.docx4j.wml.Body;import org.docx4j.wml.CTBookmark;import org.docx4j.wml.Document;import org.docx4j.wml.Drawing;import org.docx4j.wml.ObjectFactory;import org.docx4j.wml.P;import org.docx4j.wml.R;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartUtilities;import org.jfree.chart.JFreeChart;import bels.StandardPieSectionLabelGenerator;import org.jfree.chart.plot.PiePlot;import org.jfree.data.general.DefaultPieDataset;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;import org.springframework.stereotype.Service;import mon.collect.Lists;import mon.collect.Maps;public class ExportBgServiceImpl {private static final String bookmark = "tpBookmark";// 报告图⽚位置的书签名public void exportBg(OutputStream out) {String srcPath = "D:/tp/fx.docx";String targetPath = "D:/tp/fx2.docx";String key = "$key";// 在⽂档中需要替换插⼊表格的位置XWPFDocument doc = null;File targetFile = null;try {doc = new XWPFDocument(POIXMLDocument.openPackage(srcPath));List<XWPFParagraph> paragraphList = doc.getParagraphs();if (paragraphList != null && paragraphList.size() > 0) {for (XWPFParagraph paragraph : paragraphList) {List<XWPFRun> runs = paragraph.getRuns();for (int i = 0; i < runs.size(); i++) {String text = runs.get(i).getText(0).trim();if (text != null) {if (text.indexOf(key) >= 0) {runs.get(i).setText(text.replace(key, ""), 0);XmlCursor cursor = paragraph.getCTP().newCursor();// 在指定游标位置插⼊表格XWPFTable table = doc.insertNewTbl(cursor);CTTblPr tablePr = table.getCTTbl().getTblPr();CTTblWidth width = tablePr.addNewTblW();width.setW(BigInteger.valueOf(8500));this.inserInfo(table);break;}}}}}doc.write(out);out.flush();out.close();} catch (Exception e) {throw new SysException(MON_SYSTEM_ERROR, e);}}/*** 把信息插⼊表格* @param table* @param data*/private void inserInfo(XWPFTable table) {List<DTO> data = mapper.getInfo();//需要插⼊的数据XWPFTableRow row = table.getRow(0);XWPFTableCell cell = null;for (int col = 1; col < 6; col++) {//默认会创建⼀列,即从第2列开始// 第⼀⾏创建了多少列,后续增加的⾏⾃动增加列CTTcPr cPr =row.createCell().getCTTc().addNewTcPr();CTTblWidth width = cPr.addNewTcW();if(col==1||col==2||col==4){width.setW(BigInteger.valueOf(2000));}}row.getCell(0).setText("指标");row.getCell(1).setText("指标说明");row.getCell(2).setText("公式");row.getCell(3).setText("参考值");row.getCell(4).setText("说明");row.getCell(5).setText("计算值");for(DTO item : data){row = table.createRow();row.getCell(0).setText(item.getZbmc());cell = row.getCell(1);cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));cell.setText(item.getZbsm());cell = row.getCell(2);cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));cell.setText(item.getJsgs());if(item.getCkz()!=null&&!item.getCkz().contains("$")){row.getCell(3).setText(item.getCkz());}cell = row.getCell(4);cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));cell.setText(item.getSm());row.getCell(5).setText(item.getJsjg()==null?"⽆法计算":item.getJsjg());}}}2.Controllerpublic void exportBg(HttpServletResponse response) {try {response.setContentType("application/octet-stream");String name = "报告";response.addHeader("Content-Disposition", "attachment;filename="+new String(name.getBytes(),"iso-8859-1") +".docx"); OutputStream out = response.getOutputStream();export.exportBg(out,sblsh);} catch (Exception e) {}}3.maven<dependency><groupId>org.apache.poi</groupId><artifactId>poi-excelant</artifactId><version>3.12</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.12</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.8</version></dependency><!-- ⽣成图⽚--><dependency><groupId>org.jfree</groupId><artifactId>jfreechart</artifactId><version>1.0.19</version></dependency><dependency><!--⽀持插⼊图⽚--><groupId>org.docx4j</groupId><artifactId>docx4j</artifactId><version>3.3.1</version></dependency>在⽂档中指定位置设置好关键字如 demo 中的 “$key”结果图如下:。
POI插入WORD表格
POI插入WORD表格篇一:poi操作wordpackage .haiyisoftmon.poi;import java.io.File;import java.io.;import java.io.;import java.io.;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import org.apache.poi.POIXMLDocument;importorg.apache.poi.openxml4j.exceptions.InvalidFormatExcep tion;importermodel.ParagraphAlignment;import ermodel.XWPFDocument;import ermodel.XWPFParagraph;import ermodel.XWPFRun;import ermodel.XWPFTable;import ermodel.XWPFTableCell;import ermodel.XWPFTableRow;import org.apache.xmlbeans.XmlException;import org.apache.xmlbeans.XmlToken;importorg.openxmlformats.schemas.drawingml.x2006.main.CTNonV isualDrawingProps; importorg.openxmlformats.schemas.drawingml.x2006.main.CTPosi tiveSize2D;importorg.openxmlformats.schemas.drawingml.x2006.wordprocess ingDrawing.CTInline;public class PoiWordTemplate {private XWPFDocument document;public XWPFDocument getDocument() { } return document; public void setDocument(String templatePath) { try { this.document = newXWPFDocument( POIXMLDocument.openPackage(templatePath) ); } catch (IOException e) {} // TODO Auto-generated catch block e.printStackTrace();//this.document = document;}/*** 往模板中插入图片* @param document* @param mapImage* @param width* @param height*/public void replaceTextToImage(Map<String,String> mapImage,int width,int height){ List<XWPFParagraph> listParagraphs = this.document.getParagraphs();for(int i=0;i<listParagraphs.size();i++){for (Entry<String,String> entry : mapImage.entrySet()) {if(listParagraphs.get(i).getText().trim().indexOf(entry. getKey()) != -1) { CTInline inlinelistParagraphs.get(i).createRun().getCTR().addNewDrawi ng().addNewInline();try {insertPicture(entry.getValue(),inline,width,height);} catch (InvalidFormatException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch ( e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}/*** 替换word中的文字* @param document* @param mapValue* @param newText*/public void replaceTextToText(Map<String,String> mapValue){List<XWPFRun> listRun;List<XWPFParagraph> listParagraphs =this.document.getParagraphs();for(int i=0;i<listParagraphs.size();i++){listRun = listParagraphs.get(i).getRuns();for(int j=0;j<listRun.size();j++){ =if(mapValue.get(listRun.get(j).getText(0)) != null || "null".equals(mapValue.get(listRun.get(j).getText(0))) ){listRun.get(j).setText(mapValue.get(listRun.get(j).get Text(0)),0); }}} } /*** 往表格中插入数据* @param document* @paramlist* @param position*/ public voidsetTablesValue(List<Map<String, Object>> list,int position,int columnNum) { Iterator<XWPFTable> it = this.document.getTablesIterator();int count = 0;Map<String,String> columnMap = newHashMap<String,String>();while (it.hasNext()) {XWPFTable table = (XWPFTable) it.next();if(count == position){XWPFTableRow firstRow = table.getRow(1);List<XWPFTableCell> rowCell = firstRow.getTableCells();for(int i=0;i<rowCell.size();i++){columnMap.put(i+"", rowCell.get(i).getText().trim()); } table.removeRow(1);//删除第二行 for(inti=0;i<list.size();i++){XWPFTableRow row =table.createRow();//创建新的一行时创建了第row.setHeight(30);/* for(int j=0;j<=columnNum-2;j++){row.addNewTableCell();}*/ 一个cell}int rcount = table.getNumberOfRows(); for (int i = 1;i < rcount; i++) {XWPFTableRow newRow =table.getRow(i);List<XWPFTableCell> cells =newRow.getTableCells();for(intj=0;j<cells.size();j++){cells.get(j).setText(list.get(i-1).get(columnMap.get(j+""))+"");//标题栏不用改变单元格的值}}}count++;}}/*** 设置用电建议书里的基本信息第一个表格*/public void setOfferBorkBasicInfo(Map<String, Object> map,List<Map<String, Object>> list,int position){Iterator<XWPFTable> it =this.document.getTablesIterator();int count = 0;Map<String,String> columnMap = newHashMap<String,String>();while (it.hasNext()) {XWPFTable table = (XWPFTable) it.next();if(count == position){int rcount = table.getNumberOfRows();for (int i = 0; i < rcount; i++){if(i<=4){ XWPFTableRow newRow = table.getRow(i);List<XWPFTableCell> cells = newRow.getTableCells(); for(intj=0;j<cells.size();j++){if(!"null".equals(map.get(cell s.get(j).getText().trim())+"")){String temp =cells.get(j).getText().trim()+"";cells.get(j).removePa ragraph(0);cells.get(j).setText(map.get(temp)+""); } } } } XWPFTableRow sixRow = table.getRow(6);List<XWPFTableCell> rowCell = sixRow.getTableCells(); for(int i=0;i<rowCell.size();i++){columnMap.put(i+"",rowCell.get(i).getText().trim()); } for(inti=0;i<list.size();i++){XWPFTableRow row = table.createRow();//创建新的一行时创建了第row.setHeight(35);for(int j=0;j<=6;j++){row.addNewTableCell();}一个cell} table.removeRow(6);//删除模板中的字段行 int rowCount = table.getNumberOfRows(); int k= 0; for (int i = 6; i < rowCount; i++) {XWPFTableRow tempRow =table.getRow(i);List<XWPFTableCell> cells = tempRow.getTableCells();for(intj=0;j<cells.size();j++){//cells.get(j).removeParagraph(0);cells.get(j).setText(list.get(k).get(columnMap.get(j+" "))+"");}k++;}}count++;}}/*** 生成用电分析结果与优化用电建议* @param list*@param position*/ public voidsetAnanlyResultTbl(List<String> list,intposition){Iterator<XWPFTable> it =this.document.getTablesIterator();int count = 0;while (it.hasNext()) {XWPFTable table = (XWPFTable) it.next(); if(count == position){ XWPFTableRow tempRow = table.getRow(1);List<XWPFTableCell> cellList = tempRow.getTableCells(); XWPFTableCell cell = cellList.get(0);List<XWPFParagraph> listGraph = cell.getParagraphs();篇二:poi导出WORD表格居中不废话,直接上代码XWPFDocument doc = newXWPFDocument(); XWPFTabletable = doc.createTable(5, 5);CTTblPrtablePr =table.getCTTbl().addNewTblPr();tablePr.addNewJc().setVal(STJc.CENTER);篇三:POI--WORD部分的示例Apache POI----Word部分最近在研究Apache POI,不过只研究了如何做word的部分。
居中表头的方法
居中表头的方法
居中表头的方法有以下几种:
1.使用格式刷:在Excel表格中选择表头所在的单元格,然后点击“Home”选项卡中的“格式刷”按钮,在需要居中的单元格中选择一次格式刷即可完成居中操作。
2.跨列居中法:将需要居中的标题要跨列居中的单元格选中。
右击鼠标,在菜单中选择“设置单元格格式”,在对话框内选择“对齐”-“水平对齐”-“跨列居中”,点击“确定”即可。
3.合并居中:选中要合并的几个单元格,点工具栏中“合并后居中”,标题即居中。
4.行高控制:如果表头的headertext中只有一行的标题,没有多行的标题,那么在gridview的第一个属性中填写一个属性即可居中。
具体来说,应该就是可以居中了:.header { line-height:40px; }
<HeaderStyle CssClass="<spanstyle="font-family: Arial, Helvetica, sans-serif;">header</span>" /> 用行高控制,即可。
以上方法仅供参考,建议根据实际情况选择合适的方法。
poi setalignment方法
poi setalignment方法POI是一款Java语言的开源组件,用于操作Microsoft Office格式的文件,如Excel、Word和PowerPoint等。
其中,POI的Excel部分提供了丰富的API来操作Excel文件,包括读取、写入、修改等。
在实际应用中,我们常常需要对Excel表格进行格式化处理,比如设置单元格的对齐方式。
本文将详细介绍POI中设置单元格对齐方式的方法——setAlignment()。
一、什么是setAlignment()方法setAlignment()方法是POI中HSSFCellStyle类和XSSFCellStyle类中的一个方法,用于设置单元格内容在水平方向和垂直方向上的对齐方式。
其中,HSSFCellStyle类用于操作.xls格式的Excel文件,而XSSFCellStyle类用于操作.xlsx格式的Excel文件。
二、setAlignment()方法详解setAlignment()方法具有以下几个重要参数:1. 水平方向上对齐方式(HorizontalAlignment):可选值为LEFT、CENTER、RIGHT、FILL、JUSTIFY和CENTER_SELECTION。
2. 垂直方向上对齐方式(VerticalAlignment):可选值为TOP、CENTER、BOTTOM和JUSTIFY。
3. 换行标志(WrapText):当单元格内容超过单元格宽度时是否自动换行,默认为false。
4. 缩进值(Indention):当单元格内容换行时第二行起始位置相对于第一行起始位置的偏移量,默认为0。
5. 文字旋转角度(Rotation):文字在单元格中的旋转角度,取值范围为-90到90度,默认为0。
6. 自动换行标志(ShrinkToFit):当单元格内容超过单元格宽度时是否自动缩小字体以适应单元格宽度,默认为false。
三、setAlignment()方法使用示例下面我们通过一个示例来演示如何使用setAlignment()方法设置单元格对齐方式。
poi导出word表格跨行
poi导出word表格跨⾏DataCommon.javapackage com.ksource.pwlp.model.statistic;public class DataCommon {private Long id;private String name;private String otherName;private String dataName;private String otherDataName;private int value;private float otherValue;private double othersValue;private String dataValue;private Long otherDataValue;private int oneResult;private int twoResult;private int threeResult;private int fourResult;private int fiveResult;private int sixResult;private float oneValue;private float twoValue;private float threeValue;private float fourValue;private float fiveValue;private float sixValue;private double oneVal;private double twoVal;private double threeVal;private double fourVal;private double fiveVal;private double sixVal;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public String getOtherName() {return otherName;}public void setOtherName(String otherName) {this.otherName = otherName;}public String getDataName() {return dataName;}public void setDataName(String dataName) {this.dataName = dataName;}public String getOtherDataName() {return otherDataName;}public void setOtherDataName(String otherDataName) {this.otherDataName = otherDataName;}public int getValue() {return value;}public void setValue(int value) {this.value = value;}public float getOtherValue() {return otherValue;}public void setOtherValue(float otherValue) {this.otherValue = otherValue;}public double getOthersValue() {return othersValue;}public void setOthersValue(double othersValue) {this.othersValue = othersValue;}public String getDataValue() {return dataValue;}public void setDataValue(String dataValue) {this.dataValue = dataValue;}public Long getOtherDataValue() {return otherDataValue;}public void setOtherDataValue(Long otherDataValue) { this.otherDataValue = otherDataValue;}public int getOneResult() {return oneResult;}public void setOneResult(int oneResult) {this.oneResult = oneResult;}public int getTwoResult() {return twoResult;}public void setTwoResult(int twoResult) {this.twoResult = twoResult;}public int getThreeResult() {return threeResult;}public void setThreeResult(int threeResult) {this.threeResult = threeResult;}public int getFourResult() {return fourResult;}public void setFourResult(int fourResult) {this.fourResult = fourResult;}public int getFiveResult() {return fiveResult;}public void setFiveResult(int fiveResult) {this.fiveResult = fiveResult;}public int getSixResult() {return sixResult;}public void setSixResult(int sixResult) {this.sixResult = sixResult;}public float getOneValue() {return oneValue;}public void setOneValue(float oneValue) {this.oneValue = oneValue;}public float getTwoValue() {return twoValue;}public void setTwoValue(float twoValue) {this.twoValue = twoValue;}public float getThreeValue() {return threeValue;}public void setThreeValue(float threeValue) {this.threeValue = threeValue;}public float getFourValue() {return fourValue;}public void setFourValue(float fourValue) {this.fourValue = fourValue;}public float getFiveValue() {return fiveValue;}public void setFiveValue(float fiveValue) {this.fiveValue = fiveValue;}public float getSixValue() {return sixValue;}public void setSixValue(float sixValue) {this.sixValue = sixValue;}public double getOneVal() {return oneVal;}public void setOneVal(double oneVal) {this.oneVal = oneVal;}public double getTwoVal() {return twoVal;}public void setTwoVal(double twoVal) {this.twoVal = twoVal;}public double getThreeVal() {return threeVal;}public void setThreeVal(double threeVal) {this.threeVal = threeVal;}public double getFourVal() {return fourVal;}public void setFourVal(double fourVal) {this.fourVal = fourVal;}public double getFiveVal() {return fiveVal;}public void setFiveVal(double fiveVal) {this.fiveVal = fiveVal;}public double getSixVal() {return sixVal;}public void setSixVal(double sixVal) {this.sixVal = sixVal;}}调⽤导出word表格代码如下:List<DataCommon> dataCommonList = new ArrayList<DataCommon>(); //数据是从数据库查出来取需要字段的值存⼊DataCommon中后存到dataCommonList中 dataCommon.setName("类别列的值");dataCommon.setOtherName("证据名称的值");dataCommonList.add(dataCommon); //dataCommonList中存的值有⼀定规律,相同类别的是紧邻挨着的String savePath = this.attachPath + File.separator + ContextUtil.getCurrentUser().getAccount() + "\\" + System.currentTimeMillis() + ".docx";new CreateTable().createSimpleTable(dataCommonList,savePath);导出word表格⽅法如下:package com.ksource.pwlp.util;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.math.BigInteger;import java.util.List;import ermodel.ParagraphAlignment;import ermodel.XWPFDocument;import ermodel.XWPFParagraph;import ermodel.XWPFRun;import ermodel.XWPFTable;import ermodel.XWPFTableCell;import ermodel.XWPFTableRow;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;import com.ksource.core.util.ContextUtil;import com.ksource.pwlp.model.statistic.DataCommon;/*** 创建证据材料清单表格* @author dxy**/public class CreateTable {public void createSimpleTable(List<DataCommon> dataCommonList, String savePath) throws Exception { String orgName = ContextUtil.getCurrentOrg().getOrgName();XWPFDocument xdoc = new XWPFDocument();XWPFParagraph xp = xdoc.createParagraph();xp.setSpacingBefore(0);XWPFRun r1 = xp.createRun();XWPFRun r2 = xp.createRun();r1.setText(orgName);r1.setFontFamily("宋体");r1.setFontSize(18);r1.addBreak(); // 换⾏r2.setText("证据清单");r2.setFontFamily("宋体");r2.setFontSize(22);r2.setTextPosition(10);r2.setBold(true);r2.addBreak(); // 换⾏xp.setAlignment(ParagraphAlignment.CENTER);Integer col_total_count = 4; // 表格最多的列数XWPFTable xTable = xdoc.createTable(1, col_total_count);CTTbl ttbl = xTable.getCTTbl();CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();tblWidth.setW(new BigInteger("8600"));tblWidth.setType(STTblWidth.DXA);// 创建表头数据int i = 0;xTable.getRow(i).setHeight(500);setCellText(xdoc, xTable.getRow(i).getCell(0), "序号", "FFFFFF", getCellWidth(0));setCellText(xdoc, xTable.getRow(i).getCell(1), "类别", "FFFFFF", getCellWidth(1));setCellText(xdoc, xTable.getRow(i).getCell(2), "证据名称", "FFFFFF", getCellWidth(2));setCellText(xdoc, xTable.getRow(i).getCell(3), "备注", "FFFFFF", getCellWidth(3));// 创建表格内容i++;String preGroupName = "";String groupName = "";int flag = 0;int num = 1;for (int i2 = i; i2 < dataCommonList.size()+1; i2++) {XWPFTableRow row = xTable.insertNewTableRow(i2);row.setHeight(450);for (int j = 0, j2 = 0; j < col_total_count; j++, j2++) {XWPFTableCell cell = row.createCell();CTTc cttc = cell.getCTTc();CTTcPr cellPr = cttc.addNewTcPr();cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);cellPr.addNewTcW().setW(BigInteger.valueOf(getCellWidth(j2)));if (j == 0) {if(preGroupName.equals(groupName)){cell.setText(String.valueOf(num));}else{cell.setText(String.valueOf(++num));}}if (j == 1) {cell.setText(dataCommonList.get(i2-1).getName());if(i2 > 1){preGroupName = dataCommonList.get(i2-2).getName();}groupName = dataCommonList.get(i2-1).getName();}if (j == 2) {cell.setText(dataCommonList.get(i2-1).getOtherName());}if (j == 3) {cell.setText("");}}if(preGroupName.equals(groupName) && !"".equals(groupName)){flag++;if(i2 == dataCommonList.size()){mergeCellsVertically(xTable, 0, i2-flag, i2);mergeCellsVertically(xTable, 1, i2-flag, i2);flag = 0;}}else{if(flag > 0){if(i2 < dataCommonList.size()){if(i2 > 1 && !"".equals(preGroupName)){mergeCellsVertically(xTable, 0, i2-1-flag, i2-1);mergeCellsVertically(xTable, 1, i2-1-flag, i2-1);flag = 0;}}if(i2 == dataCommonList.size()){mergeCellsVertically(xTable, 0, i2-1-flag, i2-1);mergeCellsVertically(xTable, 1, i2-1-flag, i2-1);flag = 0;}}}}FileOutputStream fos = new FileOutputStream(savePath);xdoc.write(fos);fos.close();}/*** 设置表头内容* @param xDocument* @param cell* @param text* @param bgcolor* @param width*/private static void setCellText(XWPFDocument xdoc, XWPFTableCell cell,String text, String bgcolor, int width) {CTTc cttc = cell.getCTTc();CTTcPr cellPr = cttc.addNewTcPr();cellPr.addNewTcW().setW(BigInteger.valueOf(width));XWPFParagraph paragraph = cell.getParagraphs().get(0);paragraph.setAlignment(ParagraphAlignment.CENTER); //设置表头单元格居中 XWPFRun run = paragraph.createRun();run.setFontFamily("仿宋_GB2312");run.setFontSize(16); //设置表头单元格字号//run.setBold(true); //设置表头单元格加粗run.setText(text);}/*** 设置列宽** @param index* @return*/private static int getCellWidth(int index) {int cwidth = 1000;if (index == 0) {cwidth = 1000;} else if (index == 1) {cwidth = 2100;} else if (index == 2) {cwidth = 3200;} else if (index == 3) {cwidth = 2100;}return cwidth;}/*** 跨⾏合并** @param table* @param col* @param fromRow* @param toRow*/public static void mergeCellsVertically(XWPFTable table, int col,int fromRow, int toRow) {for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {XWPFTableCell cell = table.getRow(rowIndex).getCell(col);if (rowIndex == fromRow) {// The first merged cell is set with RESTART merge valuecell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);} else {// Cells which join (merge) the first one, are set with CONTINUE cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);}}}/*** 将⽂件转换成byte数组* @param filePath* @return*/public byte[] fileToByte(File file){byte[] buffer = null;try{FileInputStream fis = new FileInputStream(file);ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] b = new byte[1024];int n;while ((n = fis.read(b)) != -1){bos.write(b, 0, n);}fis.close();bos.close();buffer = bos.toByteArray();}catch (FileNotFoundException e){e.printStackTrace();}catch (IOException e){e.printStackTrace();}return buffer;}}导出效果图如下:。
word模板内容的替换和生成word表格(使用poi)
word模板内容的替换和⽣成word表格(使⽤poi)1. maven 相关依赖和模板<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.15-beta2</version></dependency><!-- https:///artifact/org.apache.poi/ooxml-schemas --><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.1</version></dependency>2. ⼯具类中的⽅法// 给⽣成的表格设置样式public static void setCellWitchAndAlign(XWPFTableCell cell,String width,STVerticalJc.Enum typeEnum,STJc.Enum align){CTTc cttc = cell.getCTTc();CTTcPr ctPr = cttc.addNewTcPr();ctPr.addNewVAlign().setVal(typeEnum);cttc.getPList().get(0).addNewPPr().addNewJc().setVal(align);CTTblWidth ctTblWidth = (ctPr != null && ctPr.isSetTcW() && ctPr.getTcW()!=null &&ctPr.getTcW().getW()!=null) ? ctPr.getTcW(): ctPr.addNewTcW();if(StringUtils.isNotBlank(width)){ctTblWidth.setW(new BigInteger(width));ctTblWidth.setType(STTblWidth.DXA);}}/*** ⽣成word⽂档下载*/public static void DownloadWord(HttpServletResponse response,List<DisUser> list, Map<String, Object> map,String file){XWPFDocument document = null;ServletOutputStream servletOS = null;ByteArrayOutputStream ostream = null;//添加表格try {servletOS = response.getOutputStream();ostream = new ByteArrayOutputStream();document = new XWPFDocument(POIXMLDocument.openPackage(file));// ⽣成word⽂档并读取模板/* ***********************⽐赛报名表基本信息******************************begin */Iterator<XWPFTable> it = document.getTablesIterator();//表格内容替换添加while(it.hasNext()){XWPFTable table = it.next();int rcount = table.getNumberOfRows();for(int i =0 ;i < rcount;i++){XWPFTableRow row = table.getRow(i);List<XWPFTableCell> cells = row.getTableCells();for (XWPFTableCell cell : cells){for(Entry<String, Object> e : map.entrySet()){if (cell.getText().equals(e.getKey())){//删除原来内容cell.removeParagraph(0);//写⼊新内容cell.setText((String) e.getValue());}}}}}//换⾏XWPFParagraph paragraph2 = document.createParagraph();XWPFRun paragraphRun2 = paragraph2.createRun();paragraphRun2.setText("\r");/* ***********************⽐赛报名表基本信息******************************end *///添加标题XWPFParagraph titleParagraph2 = document.createParagraph();//设置段落靠左titleParagraph2.setAlignment(ParagraphAlignment.LEFT);XWPFRun titleParagraphRun2 = titleParagraph2.createRun();titleParagraphRun2.setText("附:作品清单");titleParagraphRun2.setColor("000000");titleParagraphRun2.setFontSize(10);//附表格XWPFTable ComTable = document.createTable();//列宽⾃动分割/*CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();comTableWidth.setType(STTblWidth.DXA);comTableWidth.setW(BigInteger.valueOf(9072));*///表格第⼀⾏XWPFTableRow comTableRowOne = ComTable.getRow(0);// 表格标题内容的填充// 因为document.createTable() 创建表格后默认是⼀⾏⼀列,所以第⼀⾏第⼀列是直接comTableRowOne.getCell(0).setText("序号"); 赋值的。
POI批量生成Word文档表格
POI批量⽣成Word⽂档表格 前⾔ 当我们在写设计⽂档,或者是其他涉及到数据架构、表结构时,可以⽤POI来批量⽣成表格,例如下⾯的表格 代码编写 引⼊POI依赖<!-- 引⼊apache poi --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.0.1</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.0.1</version></dependency> 封装两个⼯具类 ExcelUtil,POI操作Excel⼯具类import ermodel.*;import ermodel.*;import org.apache.poi.ss.util.CellRangeAddress;import ermodel.XSSFRow;import ermodel.XSSFSheet;import ermodel.XSSFWorkbook;import org.springframework.util.StringUtils;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.text.DecimalFormat;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/*** POI操作Excel⼯具类*/public class ExcelUtil {/*** 读取指定Sheet页的数据*/public static List<Map<String,String>> readExcel3(File file, int sheetIndex) throws Exception {try (FileInputStream fs = new FileInputStream(file)) {XSSFWorkbook hw = new XSSFWorkbook(fs);XSSFSheet sheet = hw.getSheetAt(sheetIndex);ArrayList<Map<String,String>> list = new ArrayList<>();//读取表头List<String> headerList = new ArrayList<String>();XSSFRow headerRow = sheet.getRow(0);for (int j = 0; j < headerRow.getLastCellNum(); j++) {String val = getCellValue(headerRow,headerRow.getCell(j));//数据为空if (StringUtils.isEmpty(val)) {continue;}headerList.add(val);}//读取数据for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {XSSFRow dataRow = sheet.getRow(i);if (dataRow == null) {continue;}HashMap<String, String> map = new HashMap<>();for (int j = 0; j < headerList.size(); j++) {String header = headerList.get(j);String val = getCellValue(dataRow,dataRow.getCell(j));map.put(header, val);}list.add(map);}return list;}}/*** 获取单元格内容*/private static String getCellValue(XSSFRow dataRow, Cell cell){String cellvalue = "";if (cell!=null) {switch (cell.getCellType()) {case BOOLEAN:cellvalue = String.valueOf(cell.getBooleanCellValue());break;case NUMERIC:cellvalue = String.valueOf(cell.getNumericCellValue()).split("\\.")[0];if(cellvalue.toLowerCase().contains("e")){cellvalue = new DecimalFormat("#").format(cell.getNumericCellValue());if(cellvalue.toLowerCase().contains("e")){throw new RuntimeException(dataRow.getCell(4) + "/数值带E");}}break;case STRING:cellvalue = cell.getStringCellValue();break;case BLANK:break;case ERROR:cellvalue = String.valueOf(cell.getErrorCellValue());break;case FORMULA:try {cellvalue = String.valueOf(cell.getNumericCellValue());} catch (IllegalStateException e) {if (e.getMessage().contains("from a STRING cell")) {try {cellvalue = String.valueOf(cell.getStringCellValue());} catch (IllegalStateException e2) {throw new RuntimeException("公式计算出错");}}}break;default:cellvalue = String.valueOf(cell.getBooleanCellValue());break;}}return cellvalue;}/*** 只⽀持⼀级表头** @param file ⽂件* @param titleName 表标题* @param columnNames 列名集合,key是⽤来设置填充数据时对应单元格的值,label就是对应的列名,⽣成Excel表时,* 第⼀维数组下标0对应值为Excel表最左边的列的列名例:{ { key,label },{ key,label } }* @param dataLists 数据集合,key对应的是列名集合的key,value是要填充到单元格的值例:ArrayList<HashMap<String key, String vaule>> */public static String createExcelFile(File file,String titleName, String[][] columnNames, ArrayList<HashMap<String, String>> dataLists) { //创建HSSFWorkbook对象(excel的⽂档对象)HSSFWorkbook wb = new HSSFWorkbook();//建⽴新的sheet对象(excel的表单)HSSFSheet sheet = wb.createSheet(titleName);//设置表单名//1、标题名//创建标题⾏,参数为⾏索引(excel的⾏),可以是0~65535之间的任何⼀个HSSFRow row1 = sheet.createRow(0);createCell(row1, 0, titleName);//合并单元格CellRangeAddress构造参数依次表⽰起始⾏,截⾄⾏,起始列,截⾄列sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnNames.length - 1));//2、列名//创建列名⾏HSSFRow row2 = sheet.createRow(1);for (int i = 0; i < columnNames.length; i++) {//单元格宽度sheet.setColumnWidth(i, 20 * 256);createCell(row2, i, columnNames[i][1]);//例:[[key,label],[key,label]] 取label}//3、填充数据int index = 2;//标题⾏、列名⾏,所以数据⾏默认从第三⾏开始for (HashMap<String, String> map : dataLists) {//创建内容⾏HSSFRow row3 = sheet.createRow(index);for (int i = 0; i < columnNames.length; i++) {String val = map.get(columnNames[i][0]);createCell(row3, i, val == null ? "" : val);//例:[[key,label],[key,label]] 取key}index++;}try(FileOutputStream outputStream = new FileOutputStream(file)) {wb.write(outputStream);} catch (IOException e) {e.printStackTrace();}return file.getName()+" 创建成功";}/*** 创建⼀个单元格*/private static void createCell(Row row, int column, String text) {Cell cell = row.createCell(column); // 创建单元格cell.setCellValue(text); // 设置值}} WordUtil,POI操作Word⼯具类import ermodel.*;import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;import java.math.BigInteger;import java.util.List;import java.util.Map;/*** POI操作Word⼯具类*/public class WordUtil {/*** 简单表格⽣成* @param xdoc XWPFDocument对象* @param titles 表头表头* @param values 表内容*/public static void createSimpleTable(XWPFDocument xdoc,String[] titles,List<Map<String, String>> values){ //⾏⾼int rowHeight = 300;//开始创建表格(默认有⼀⾏⼀列)XWPFTable xTable = xdoc.createTable();CTTbl ctTbl = xTable.getCTTbl();CTTblPr tblPr = ctTbl.getTblPr() == null ? ctTbl.addNewTblPr() : ctTbl.getTblPr();CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();tblWidth.setType(STTblWidth.DXA);tblWidth.setW(new BigInteger("8600"));//表格宽度// 创建表头数据XWPFTableRow titleRow = xTable.getRow(0);titleRow.setHeight(rowHeight);for (int i = 0; i < titles.length; i++) {setCellText(i == 0 ? titleRow.getCell(0) :titleRow.createCell(), titles[i]);}// 创建表格内容for (int i = 0; i < values.size(); i++) {Map<String, String> stringStringMap = values.get(i);//设置列内容XWPFTableRow row = xTable.insertNewTableRow(i + 1);row.setHeight(rowHeight);for (String title : titles) {setCellText(row.createCell(), stringStringMap.get(title));}}}/*** 设置列内容*/private static void setCellText(XWPFTableCell cell,String text) {CTTc cttc = cell.getCTTc();CTTcPr cellPr = cttc.addNewTcPr();cellPr.addNewTcW().setW(new BigInteger("2100"));cell.setColor("FFFFFF");cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);CTTcPr ctPr = cttc.addNewTcPr();ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);cell.setText(text);}} ⾸先写sql脚本,查出所有表结构信息(表名称、表注释、表字段数据等)-- mysql查询表名、表注释、表字段数据SELECTt.table_name AS'表名称',t.table_comment AS'表注释',c.column_name AS'字段名称',c.column_type AS'数据类型',c.column_comment AS'字段注释',c.column_key AS'是否主键',c.is_nullable AS'是否允许NULL'FROMinformation_schema.COLUMNS cJOIN information_schema.TABLES t ON c.table_name = t.table_nameWHEREc.table_schema = (SELECT DATABASE()); 把结果集拷贝到Excel中 前期⼯作准备完毕,接下来开始⼲正事import ermodel.XWPFDocument;import ermodel.XWPFParagraph;import ermodel.XWPFRun;import java.io.File;import java.io.FileOutputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class Test {private static void tables(){try {XWPFDocument xdoc = new XWPFDocument();HashMap<String, List<Map<String, String>>> hashMap = new HashMap<>();//获取数据/*-- mysql查询表名、表注释、表字段数据SELECTt.table_name AS '表名称',t.table_comment AS '表注释',c.column_name AS '字段名称',c.column_type AS '数据类型',c.column_comment AS '字段注释',c.column_key AS '是否主键',c.is_nullable AS '是否允许NULL'FROMinformation_schema.COLUMNS cJOIN information_schema.TABLES t ON c.table_name = t.table_name WHEREc.table_schema = (SELECT DATABASE());*/File file = new File("E:\\TestExcel01.xlsx");List<Map<String, String>> list = ExcelUtil.readExcel3(file, 0);//处理数据,调整成下⾯的格式/*[{"表名称":[{},//⼀条条字段信息{},//⼀条条字段信息{},//⼀条条字段信息]}]*/ArrayList<Map<String, String>> arrayList = new ArrayList<>();String tableName = "";for (int i = 0; i < list.size(); i++) {Map<String, String> map = list.get(i);String tName = String.valueOf(map.get("表名称"));if(tableName.equals(tName)){arrayList.add(map);}else{hashMap.put(tableName,arrayList);tableName = tName;arrayList = new ArrayList<>();arrayList.add(map);}if(list.size() - i == 1){hashMap.put(tableName,arrayList);}}//⽣成内容for (String tName : hashMap.keySet()) {if("".equals(tName)){continue;}List<Map<String, String>> maps = hashMap.get(tName);String tZs = String.valueOf(maps.get(0).get("表注释"));//设置⽂字,对表格进⾏描述XWPFParagraph xp = xdoc.createParagraph();xp.setSpacingBefore(0);XWPFRun r1 = xp.createRun();r1.setFontFamily("宋体");r1.setFontSize(12);r1.setTextPosition(0);r1.addBreak(); // 换⾏r1.setText("表名称:"+tName);r1.addBreak(); // 换⾏r1.setText("表注释:"+tZs);//表格标题String[] titles = {"字段名称","字段类型","字段注释","允许空值",};//表格内容List<Map<String, String>> values = new ArrayList<>();for (Map<String, String> stringStringMap : maps) {String cName = stringStringMap.get("字段名称");String cType = stringStringMap.get("数据类型");String cZs = stringStringMap.get("字段注释");String isPri = stringStringMap.get("是否主键");String isNull = stringStringMap.get("是否允许NULL");//按照表格标题格式进⾏封装HashMap<String, String> stringStringHashMap = new HashMap<>();stringStringHashMap.put("字段名称",cName);stringStringHashMap.put("字段类型",cType);stringStringHashMap.put("字段注释",cZs);stringStringHashMap.put("允许空值",isNull);values.add(stringStringHashMap);}WordUtil.createSimpleTable(xdoc, titles, values);}//保存word⽂件FileOutputStream fos = new FileOutputStream("E:\\Test1.doc");xdoc.write(fos);fos.close();System.out.println("操作完成!");}catch (Exception e){e.printStackTrace();}}public static void main(String[] args) {tables();}} 运⾏main进⾏测试public static void main(String[] args) {tables();} 效果 后记 通过使⽤POI,批量⽣成表格,⽅便快捷、省⼼⾼效,项⽬经理⽤了都说好!。
数据导出生成word附件使用POI的XWPFTemplate对象
数据导出⽣成word附件使⽤POI的XWPFTemplate对象⽐较常⽤的实现Java导⼊、导出Excel的技术有两种Jakarta POI和Java Excel。
Jakarta POI 是⼀套⽤于访问微软格式⽂档的Java API。
Jakarta POI有很多组件组成,其中有⽤于操作Excel格式⽂件的HSSF和⽤于操作Word的HWPF;⼀、前端使⽤get请求和post请求都可以get请求:window.location.href= appPath+"/export/handoverForm?ticketId="+self.ticketId +"&complainId="+row.id+"&formCode="+plainDetail;隐藏form表单改写成post请求,form表单get和post都可以:<form id="exportForm" action="/service/xfComplain/exportCaseLedger" method="post"><input type="hidden" name="dataRange" id="dataRange"/><input type="hidden" name="processStatus" id="processStatus"/><input type="hidden" name="cantonCode" id="cantonCode"/><input type="hidden" name="startDate" id="startDate"/><input type="hidden" name="endDate" id="endDate"/><input type="hidden" name="multiFildMatch" id="multiFildMatch"/></form>$("#dataRange").val(self.table.pageData.dataRange);$("#processStatus").val(self.table.pageData.processStatus);$("#startDate").val(self.table.pageData.startDate);$("#endDate").val(self.table.pageData.endDate);$("#multiFildMatch").val(self.table.pageData.multiFildMatch);$('#exportForm').submit();⼆、java代码@ResponseBody@RequestMapping("/exportWord")public void exportHandoverForm(HttpServletRequest request,HttpServletResponse response, ExportParam exportParam) {String projectPath = getProjectPath(request);String templateFile = getTemplateFile(exportParam, projectPath, request);Map<String, Object> data = new HashMap<>();File file = null;InputStream in = null;ServletOutputStream out = null;try {// 数据源HandoverModel handoverModel = getHandoverFormData(exportParam.getComplainId());// 反射机制,获取所有属性对象,在拿到属性值,设置数据for (Field field : HandoverModel.class.getDeclaredFields()) {// 暴⼒反射,不是public修饰的属性也要获取field.setAccessible(true);data.put(field.getName(), field.get(handoverModel));}// 数据源组成map键值对形式data.put("reportorList", handoverModel.getReportorList().getDatas());String fileName = handoverModel.getCaseCode();String exportFilePath = projectPath + ExportConstant.DEFAULT_EXPORT_PATH;("----------templateFile:" + templateFile);("-----------projectPath:" + projectPath);// Configure对象是处理表格数据,可以⾃适应⽣成对应⾏数数据Configure config = Configure.newBuilder().customPolicy("reportorList", new FileTablePolicy()).build();// XWPFTemplate对象是处理word⽂档对象,根据map数据源的键值对渲染⽂档数据XWPFTemplate template = pile(templateFile, config).render(data);// ⽂件⽣成到本地,先⽣成好⽂档,再读取到内存中响应给前台String downloadFileName = fileName + ".docx";File outPutFile = new File(exportFilePath);if (!outPutFile.exists()) {outPutFile.mkdirs();}FileOutputStream outFile = new FileOutputStream(exportFilePath + downloadFileName);template.write(outFile);outFile.flush();outFile.close();template.close();// 通过⽂件流读取到⽂件,再将⽂件通过response的输出流,返回给页⾯下载file = new File(projectPath + ExportConstant.DEFAULT_EXPORT_PATH + downloadFileName); in = new FileInputStream(file);response.setCharacterEncoding("utf-8");response.setContentType("application/msword");response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(downloadFileName, "UTF-8"))));out = response.getOutputStream();byte[] buffer = new byte[512];int bytesToRead = -1;// ⽤响应对象response中的输出流读取⽣成好的⽂件while ((bytesToRead = in.read(buffer)) != -1) {out.write(buffer, 0, bytesToRead);}} catch (Exception e) {logger.error("导出word出错", e);} finally {if (in != null) try {in.close();if (out != null) out.close();if (file != null) file.delete(); // 删除临时⽂件} catch (IOException e) {logger.error("删除删除临时⽂件出错", e);}}}使⽤XWPFTemplate引擎,插件化Configure插⼊表格;三、不需要插⼊表格:XWPFTemplate template = pile(templateFile).render(data);。
poi操作doc文档
poi操作doc⽂档接到⼀个需求⽤word⽂档做⼀个批量导⼊,我当时⽤了两⼤种⽅法,第⼀:jacob技术,确实挺好⽤不管是docx和doc互相转换还是转html都可以,docx的公式也能解决,但是有⼀个致命的问题只能在windows上使⽤,liunx的直接可以略过了,应为只能在windows上使⽤的缘故,只⼤致写了⼀些,需要jacob包和⼀个dll⽂件, dll⽂件放在system32这个⽬录下⾯,这也是为什么只能在windows上使⽤的原因,⼤家可以取官⽹下载,也可以留下邮箱发你import com.jacob.activeX.ActiveXComponent;import .Dispatch;import .Variant;/*** @author shihao* @Title: JacobUtil* @ProjectName Second-order-center* @Description:* @date Created in* @Version: $*/public class JacobUtil {public static final int WORD_HTML = 8;public static final int WORD_TXT = 7;public static final int EXCEL_HTML = 44;/*** WORD转HTML** @param docfile* WORD⽂件全路径* @param htmlfile* 转换后HTML存放路径*/public void wordToHtml(String docfile, String htmlfile) {ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动wordtry {// 设置word不可见app.setProperty("Visible", new Variant(false));//获得documents对象Dispatch docs = (Dispatch) app.getProperty("Documents").toDispatch();//打开⽂件Dispatch doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] { docfile, new Variant(false),new Variant(true) }, new int[1]).toDispatch();//保存新的⽂件Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {htmlfile, new Variant(WORD_HTML) }, new int[1]);Variant f = new Variant(false);Dispatch.call(doc, "Close", f);} catch (Exception e) {e.printStackTrace();} finally {app.invoke("Quit", new Variant[] {});}}}第⼆:poi操作 poi读写word不同版本是不⼀样的,我当时是docx和docdocx版本使⽤XWPFDocumentimport com.inxedu.wxos.util.UploadPropertyUtil;import net.arnx.wmf2svg.gdi.svg.SvgGdi;import net.arnx.wmf2svg.gdi.svg.SvgGdiException;import net.arnx.wmf2svg.gdi.wmf.WmfParseException;import net.arnx.wmf2svg.gdi.wmf.WmfParser;import org.apache.poi.xwpf.converter.core.FileImageExtractor;import org.apache.poi.xwpf.converter.core.FileURIResolver;import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;import ermodel.*;import org.jsoup.nodes.Document;import org.openxmlformats.schemas.officeDocument.x2006.math.CTOMath;import java.io.*;import java.util.List;import java.util.UUID;import java.util.zip.GZIPOutputStream;/*** @author shihao* @Title: Word* @ProjectName Second-order-center* @Description:* @date Created in* @Version: $*/*/public class Word {// public static UploadPropertyUtil propertyUtil = UploadPropertyUtil.getInstance("application-project");public String html(String paths) throws IOException, WmfParseException, SvgGdiException {// String[] sourceArray = paths.split("/");// StringBuilder p = new StringBuilder();// for (int i=0; i<sourceArray.length-1;i++){// p.append(sourceArray[i]);// p.append("/");// }// String path = propertyUtil.getProperty("project.file.root")+String.valueOf(p);// String fileName = sourceArray[sourceArray.length-1];// final String filepath = path+fileName;// String htmlName = UUID.randomUUID().toString().replaceAll("-", "")+".html";// final String file = filepath;File f = new File(paths);if (!f.exists()) {System.out.println("Sorry File does not Exists!");return "Sorry File does not Exists!";} else {if (f.getName().endsWith(".docx") || f.getName().endsWith(".DOCX")) {// 1) 加载word⽂档⽣成 XWPFDocument对象InputStream in = new FileInputStream(f);XWPFDocument document = new XWPFDocument(in);// 2) 解析 XHTML配置 (这⾥设置IURIResolver来设置图⽚存放的⽬录)File imageFolderFile = new File(path);XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));options.setExtractor(new FileImageExtractor(imageFolderFile));options.setIgnoreStylesIfUnused(false);options.setFragment(true);// 3) 将 XWPFDocument转换成XHTMLOutputStream out = new FileOutputStream(new File(path + htmlName));XHTMLConverter.getInstance().convert(document, out, options);return path+htmlName;} else {System.out.println("Enter only MS Office 2007+ files");return "Enter only MS Office 2007+ files";}}}}这个⽅法虽然可以将⽂字和图⽚转html,应该是xhtml下⾯说读取xhtml,我也能解析出来,但是客户那边⼜说了,我们要公式也要读取,找了很多资料docx的没找到好的⽅法,只好⼜换⽅法,下⾯先贴出读取xhtml的⽅法,如果乱码注意编码import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Entities;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;/*** @author shihao* @Title: XhtmltoHtml* @ProjectName Second-order-center* @Description:* @date Created in* @Version: $*/public class XhtmltoHtml {public String html2xhtml(String html) {Document doc = Jsoup.parse(html);doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml).escapeMode(Entities.EscapeMode.xhtml);return doc.html();}public String html(String path) throws IOException {File file = new File(path);FileInputStream input = new FileInputStream(file);int size = input.available();byte[] buff = new byte[size];input.read(buff);input.close();String html = new String(buff, "utf-8");System.out.println("============html===================");System.out.println(html);XhtmltoHtml xhtmltoHtml = new XhtmltoHtml();String xhtml = xhtmltoHtml.html2xhtml(html);System.out.println("============xhtml===================");System.out.println(xhtml);return xhtml;}}没办法客户就是上帝,换吧,这次是读取doc⽂档的,话不多说直接上码import com.inxedu.wxos.util.UploadPropertyUtil;public class MainTest {public static UploadPropertyUtil propertyUtil = UploadPropertyUtil.getInstance("application-project");public static void main(String[] args) throws Exception{String FilePath = "C:\\Users\\MACHENIKE\\Desktop\\Batch.doc";String path = "C:\\Users\\MACHENIKE\\Desktop\\batt";ODocument odoc = new ODocument(FilePath);writeHtml(odoc,path);// writeXml(odoc,path);System.out.println("OK!");}public static void writeHtml(ODocument doc,String path){OTable otable = new OTable(doc.getDocument());String htmlData = otable.replaceHtmlTable(doc.readDoc());OImage oimage = new OImage(doc.getDocument(),path);htmlData = oimage.replaceImg(htmlData);OPrint oprint = new OPrint();oprint.printHtml(htmlData, path,"batch.html");}public static void writeXml(ODocument doc,String path){OTable otable = new OTable(doc.getDocument());String xmlData = otable.replaceXmlTable(doc.readDoc());OImage oimage = new OImage(doc.getDocument(),path);xmlData = oimage.replaceImg(xmlData);xmlData = oimage.replaceImg(xmlData);OPrint oprint = new OPrint();oprint.printXml(xmlData, path);}}import org.apache.poi.hwpf.HWPFDocument;import ermodel.CharacterRun;import ermodel.Range;import java.io.File;import java.io.FileInputStream;import java.util.LinkedList;import java.util.List;public class ODocument {private HWPFDocument doc;private String path;private List<Integer> fontSize;private List<Integer> color;public ODocument(String path){this.doc = null;fontSize = new LinkedList<>();color = new LinkedList<>();this.path = path;this.loadDoc();}private void loadDoc(){try{FileInputStream in=new FileInputStream(new File(this.path));this.doc = new HWPFDocument(in);in.close();}catch(Exception e){System.out.println(e.getMessage());}}public HWPFDocument getDocument(){return this.doc;}public String readDoc(){String Data = "";int length = doc.characterLength();String str="";char ch;int len;for (int i = 0; i < length - 1; i++) {Range r = new Range(i,i+1,doc);CharacterRun cr = r.getCharacterRun(0);str = cr.text();Data = Data+str;len = cr.text().length();color.add(cr.getColor());fontSize.add(cr.getFontSize());while(len-->0) ch = str.charAt(len);}System.out.println(Data);return DataPretreatment(Data);}private String DataPretreatment(String Data){Data = Data.replaceAll("(\u0013.{1,30}\u0015)+","\u0002");Data = Data.replaceAll("\\b.+\u0007","@TABLE@");return Data;}}import net.arnx.wmf2svg.gdi.svg.SvgGdi;import net.arnx.wmf2svg.gdi.wmf.WmfParser;import org.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.model.PicturesTable;import ermodel.Picture;import org.w3c.dom.Document;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import java.io.*;import java.util.LinkedList;import java.util.List;import java.util.zip.GZIPOutputStream;public class OImage {public List<String> ImgPath;public List<String> ImgSize;public List<String> wmfPath;public List<String> wmfSize;private HWPFDocument doc;public String ProjectPath;public String sp;public OImage(HWPFDocument document, String path){this.ProjectPath = path;this.sp = File.separator;this.doc = document;ImgPath = new LinkedList<>();ImgSize = new LinkedList<>();wmfPath = new LinkedList<>();wmfSize = new LinkedList<>();this.readImg();}private void readImg(){int id = 0;String name = "";PicturesTable pTable = doc.getPicturesTable();List<Picture> pic = pTable.getAllPictures();for(Picture img : pic) {name = "articleImg"+id;String afileName=img.suggestFullFileName();String suffix = afileName.substring(stIndexOf(".") + 1);try{OutputStream out=new FileOutputStream(new File(ProjectPath+sp+name+"."+suffix));img.writeImageContent(out);out.close();}catch(Exception e){e.getMessage();}if(suffix.equals("wmf")) convert(ProjectPath+sp+name+"."+suffix,ProjectPath+sp+name+".svg"); if(suffix.equals("wmf")){ImgPath.add(name+".svg");wmfPath.add(name+".svg");wmfPath.add(name+".svg");wmfSize.add(img.getWidth()+"@"+img.getHeight());}else {ImgPath.add(name+"."+suffix);ImgSize.add(img.getWidth()+"@"+img.getHeight());}id++;}}public String replaceImg(String data){System.out.println("图⽚路径:"+ImgPath);String res = "<p>"+data;for(String path:ImgPath){path = "\n<img class='image' src='"+path+"'>";res = res.replaceFirst("\u0001",path);}// String[] xxx = res.split("(\\s\\d\u002e)+");// int i=1;// if(xxx[0].charAt(0)=='.') i = 0;// String path = "";// res = "";// for(;i<xxx.length;i++){// xxx[i] = i+xxx[i];// Matcher m = pile("\u0001").matcher(xxx[i]);// xxx[i] = xxx[i].trim();// while(m.find()){// xxx[i] = xxx[i].replaceFirst("\u0001","");// path = "<img class='img' src='"+ImgPath.get(index++)+"'></img>";// xxx[i] = xxx[i]+path;// }// res = res+xxx[i]+"\n\n\n\n\n\n\n";// }return res;}public void convert(String file,String dest){try{InputStream in = new FileInputStream(new File(file));WmfParser parser = new WmfParser();final SvgGdi gdi = new SvgGdi(false);parser.parse(in, gdi);Document doc = gdi.getDocument();OutputStream out = new FileOutputStream(dest);if (dest.endsWith(".svgz")) {out = new GZIPOutputStream(out);}output(doc, out);}catch(Exception e){System.out.println("edn"+e.getMessage());}}public void output(Document doc, OutputStream out) throws Exception {TransformerFactory factory = TransformerFactory.newInstance();Transformer transformer = factory.newTransformer();transformer.setOutputProperty(OutputKeys.METHOD, "xml");transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");transformer.setOutputProperty(OutputKeys.INDENT, "yes");transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"-//W3C//DTD SVG 1.0//EN");transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"); transformer.transform(new DOMSource(doc), new StreamResult(out));ByteArrayOutputStream bos = new ByteArrayOutputStream();transformer.transform(new DOMSource(doc), new StreamResult(bos));out.flush();out.close();}}import java.io.File;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.io.PrintStream;public class OPrint {public String Data = "";public String xmlData = "";public String htmlData = "";public String path;public String sp;public OPrint(){this.sp = File.separator;}public void printHtml(String Data,String path,String fileName){String str= Data.replaceAll("\\r|\\n","</p><p>");System.out.println(str);//System.out.println(htmlData);OutputStreamWriter f = null;String css1 = "../../../aStyle.css";String css2 = "../../../../aStyle.css";try{f = new OutputStreamWriter(new FileOutputStream(path+sp+fileName), "utf-8");f.append("<!DOCTYPE html>");f.append("<head>");f.append("<meta charset='utf8'>");f.append("<title>word to html</title>");f.append("<link rel='stylesheet' href='"+css1+"'>");f.append("<link rel='stylesheet' href='"+css2+"'>");f.append("</head>");f.append("<body>\n<div>");f.append(str);f.append("</div>\n</body>");f.append("</html>");f.close();}catch(Exception e){e.getMessage();}}public void printXml(String xml,String path){String[][] xmlData = dataToXML(xml);writeToXML(xmlData,path);}private String[][] dataToXML(String str){//System.out.println(Data);str = str.replaceAll("\u0005", "");str = str.replaceAll("\u0007", "");String[] data = str.split("(\\s\\d\u002e)+");int i=1;if(data[0].charAt(0)=='1') i = 0;String[][] subject = new String[data.length-i][4];String[][] subject = new String[data.length-i][4];int index = 0;for(;i<data.length;i++){int tab,ch,an;System.out.println("data:"+data[i]);tab = data[i].indexOf("\u0003");ch = data[i].indexOf("A.");an = data[i].indexOf(":");if(tab!=-1) subject[index][0] = data[i].substring(0,tab);else if(ch!=-1) subject[index][0] = data[i].substring(0,ch);else if(an!=-1) subject[index][0] = data[i].substring(0,an);else subject[index][0] = data[i];if(tab!=-1 && ch!=-1) subject[index][1] = data[i].substring(tab,ch);else if(tab!=-1 && an!=-1) subject[index][1] = data[i].substring(tab,an);else if(tab!=-1) subject[index][1] = data[i].substring(tab,data[i].length());if(ch!=-1 && an!=-1) subject[index][2] = data[i].substring(ch,an);else if(ch!=-1) subject[index][2] = data[i].substring(ch,data[i].length());if(an!=-1) subject[index][3] = data[i].substring(an,data[i].length());index++;}return subject;}private void writeToXML(String[][] xml,String path){FileOutputStream f=null;PrintStream ps=null;try{f = new FileOutputStream(path+sp+"XMLData.xml");ps = new PrintStream(f);}catch(Exception e){e.getMessage();}ps.println("<?xml version='1.0' encoding='UTF-8'?>");ps.println("<Word>");for(int i=0;i<xml.length;i++){ps.println("\t<Data>");ps.println("\t\t<Subject>");ps.println("\t\t\t"+xml[i][0].trim());ps.println("\t\t</Subject>");if(xml[i][1]!=null) ps.println("\t\t\t"+xml[i][1].trim());if(xml[i][2]!=null){ps.println("\t\t<Choose>");ps.println("\t\t\t"+xml[i][2].trim());ps.println("\t\t</Choose>");}if(xml[i][3]!=null){ps.println("\t\t<Anser>");ps.println("\t\t\t"+xml[i][3].trim());ps.println("\t\t</Anser>");}ps.println("\t</Data>\n\n");}ps.println("</Word>");}}import org.apache.poi.hwpf.HWPFDocument;import ermodel.*;import java.util.LinkedList;import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern;public class OTable {private List<String> tableData;private HWPFDocument doc;public OTable(HWPFDocument document){tableData = new LinkedList<>();this.doc = document;readTableMsg();}private void readTableMsg(){Range range = doc.getRange();TableIterator tab = new TableIterator(range);while(tab.hasNext()){Table table = tab.next();readTable(table);}}public String readTable(Table tab){String res = "";for (int i = 0; i < tab.numRows(); i++) {TableRow tr = tab.getRow(i);for (int j = 0; j < tr.numCells(); j++) {TableCell td = tr.getCell(j);for(int k=0;k<td.numParagraphs();k++){//System.out.println("k"+td.numParagraphs());Paragraph paragraph =td.getParagraph(k);res =res+ paragraph.text()+"\u0005"+"@TD@";}}res = res+"@TR@";}res = res.replaceAll("(\u0013.{1,30}\u0015)+","\u0002");tableData.add(res);return res;}public List<String> getTableData(){ //杩斿洖鏂囨。
javapoi设置生成的word的图片为上下型环绕以及其位置的实现
javapoi设置⽣成的word的图⽚为上下型环绕以及其位置的实现问题描述在使⽤poi-tl word模版⼯具时,发现⽣成的⽂档中,图⽚格式为嵌⼊型,有的图⽚甚⾄被表格遮挡⼀半。
⽽⾃⼰想要的图⽚格式为上下型环绕,并且图⽚需要居中。
问题分析poi-tl渲染图⽚,使⽤的是ermodel.XWPFRun的addPicture⽅法,该⽅法中有⼀段代码:CTInline inline =drawing.addNewInline();意思就是默认将图⽚转为inline类型,即⾏内元素。
然后我们把⽣成的嵌⼊型图⽚的⽂档转换成xml⽂件,然后再新建⼀个⽂档,插⼊图⽚后,设置图⽚为上下型环绕,保存为另⼀个xml,⽐较下两个xml的区别。
嵌⼊型图⽚的xml是:上下型环绕的图⽚的xml是我们看到两种格式的图⽚标签分别为inline和anchor。
所以如果我们想把图⽚设置为上下型环绕,需要重写poi的addPicture⽅法,把图⽚转为anchor 类型。
我们仿照ermodel.XWPFRun的addPicture⽅法,将CTInline inline = drawing.addNewInline();换成CTAnchor anchor = drawing.addNewAnchor();,然后对⽐着xml,依次对anchor的字段进⾏赋值。
结果发现⽣成的word⽆法正常打开,查了很多资料,都说poi的CTAnchor有问题,使⽤后⽆法正常打开⽣成的word。
此路不通,那我们就尝试另⼀种思路,我们不通过CTAnchor来⽣成anchor标签,⽽是直接使⽤xml,将xml赋给poi的drawing。
具体的处理⽅式在后⾯。
xml标签和图⽚格式解析在word中,在图⽚上右键,选择⼤⼩和位置,就可以看到如下界⾯:图中的上下型对应的是xml中的<wp:wrapTopAndBottom/>标签,不同环绕⽅式该标签值不⼀样。
java导出之导出word文档
java导出之导出word⽂档Springboot之word导出1.简介导出word实现⽤的⼯具是poi-tl,主要是通过预先设置word模板格式,通过数据填充来实现数据动态录⼊。
⽀持动态表格以及图。
使⽤步骤主要分为准备冰箱,准备象,把象装进冰箱。
2.准备环境(冰箱)包括两种,导包和模板预设置com.deepoove poi-tl 1.9.1 注意:poi-tl版本对阿帕奇的poi版本依赖有条件,低版本会报错,Tomcat会默认依赖低版本的jar包。
准备模板,模板可以设置⾏⾼,位置,固定宽度和最⼩⾼度,可以保证内容显⽰完全3.准备数据(⼤象)######Controller 层,返回值和两个⼊参public ResponseEntity<byte[]> exportJbZwJlxx(HttpServletRequest request, HttpServletResponse response) {//任免表⾥,需要基本信息,职务信息,部门⼈员信息,简历信息以及个⼈经历信息if(jbZwJlxxScCxDto.getDxbz()==null || "".equals(jbZwJlxxScCxDto.getDxbz()) ){log.error("档案薪酬判断标志不能为空");throw new RuntimeException("dxbz不能为空,或者为空字符串");}try {return jbZwJlxxService.getParams(jbZwJlxxScCxDto);} catch (Exception e) {log.error("导出失败",e);}return null;}######Service层获取数据,格式如下,和模板上对应即可Map<String, Object> params = new HashMap<>(100);params.put("jljj",!jlxxBean.getJljj().equals(CmGbglConstants.SPACE)? jlxxBean.getJljj() : "⽆");######动态表格的数据封装,通过**对象的属性赋值**int length = 7;// 返回数据超过七条if (res.size() > length) {length = res.size();// 封装查询回来的⼤于7的对象for (int i = 0; i < length; i++) {QtxxDto qtxxDto = new QtxxDto();qtxxDto = res.get(i);Map<String,Object> detailMap = new HashMap<String, Object>(7);detailMap.put("cw", qtxxDto.getCw());detailMap.put("name", qtxxDto.getName());qtxxDto.setCsny(getAge(qtxxDto.getCsny())+"");detailMap.put("csny", qtxxDto.getCsny());detailMap.put("zzmmmc",qtxxDto.getZzmmmc());detailMap.put("gzdwjzw",qtxxDto.getGzdwjzw());detailList.add(detailMap);qtxxDtos.add(qtxxDto);}} else {// 数据集长度⼩于七条for (int i = 0; i < res.size(); i++) {QtxxDto qtxxDto = new QtxxDto();qtxxDto = res.get(i);qtxxDto.setCsny(getAge(qtxxDto.getCsny())+"");qtxxDtos.add(qtxxDto);}for (int j = 0; j < (length - res.size()); j++) {QtxxDto qtxxDto = new QtxxDto();qtxxDtos.add(qtxxDto);}}}params.put("detailList", qtxxDtos);4.和模板建⽴关系try{//获得模板⽂件的输⼊流,这个是放在启动器的那个项⽬的resource下InputStream in = this.getClass().getResourceAsStream("/word/rmb.docx");//表格⾏循环插件HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();//绑定detailListConfigure config = Configure.builder().bind("detailList", policy).build();XWPFTemplate template = pile(in , config).render(params);String fileName = new String("rmb.docx".getBytes("UTF-8"), "iso-8859-1");ByteArrayOutputStream outputStream = new ByteArrayOutputStream();template.write(outputStream);template.close();HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.add("content-disposition", "attachment;filename=" + fileName);httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);ResponseEntity<byte[]> filebyte = new ResponseEntity<byte[]>(outputStream.toByteArray(), httpHeaders,HttpStatus.CREATED);outputStream.close();return filebyte;} catch (Exception e) {log.error("导出失败", e);throw e;}注意:模板放置的位置可以放在resource下,在本地编译的时候可以使⽤类加载器获取,但是打包到正式环境后就会找不到模板。
poixmldocumentpart 提取tables
poixmldocumentpart 提取tablesPoxmlDocumentPart是一个在.NET 的Aspose.Words库中使用的类,该库用于处理Word 文档。
如果你想从PoxmlDocumentPart中提取表格,你需要首先确保该部分确实包含表格,然后使用相应的API 来访问和提取这些表格。
下面是一个基本的示例,展示了如何使用Aspose.Words从PoxmlDocumentPart中提取表格:csharp复制代码// 假设 part 是你的 PoxmlDocumentPart 实例// 这里我们假设它包含一些表格// 获取文档中的所有段落和表格var paragraphs = part.Document.Paragraphs;var tables = part.Document.Tables;// 遍历所有的段落和表格foreach (var paragraph in paragraphs){// 如果段落包含表格,则处理它if (paragraph.HasChildNodes &¶graph.ChildNodes.FirstOrDefault(node => node is Aspose.Words.Tables.Table) isAspose.Words.Tables.Table table){// 处理表格,例如提取其内容或将其转换为其他格式// ...}}在这个例子中,我们假设PoxmlDocumentPart是一个包含Word 文档的段落和表格的实例。
我们通过遍历所有段落并检查它们是否包含子节点中的表格来提取表格。
如果找到表格,我们就可以进一步处理它。
请注意,你可能需要根据实际情况调整代码,例如,如果你的文档结构更加复杂,或者你需要处理嵌套的表格等情况。
在使用Aspose.Words时,请确保已经正确安装并引用了相应的NuGet 包。
此外,由于Aspose.Words是商业产品,你需要拥有有效的许可证才能使用它。