poi生成横向文档以及复杂表头
代码:
//创建页面并且创建横向A4XWPFDocument doc = new XWPFDocument();CTDocument1 document = doc.getDocument();CTBody body = document.getBody();if (!body.isSetSectPr()) {body.addNewSectPr();}CTSectPr section = body.getSectPr();if (!section.isSetPgSz()) {section.addNewPgSz();}CTPageSz pageSize = section.getPgSz();//必须要设置下面两个参数,否则整个的代码是无效的pageSize.setW(BigInteger.valueOf(15840));pageSize.setH(BigInteger.valueOf(12240));pageSize.setOrient(STPageOrientation.LANDSCAPE);//创建标题XWPFParagraph titleP = doc.createParagraph();titleP.setAlignment(ParagraphAlignment.CENTER);XWPFRun titleR = titleP.createRun();titleR.setText("日报(" + time + ")");titleR.setBold(true);//设置为粗体titleR.setFontFamily("华文中宋");titleR.setFontSize(14);titleR.addCarriageReturn();//创建表头XWPFTable table = doc.createTable();table.setWidth("100%");table.setWidthType(TableWidthType.PCT);//设置表格相对宽度table.setTableAlignment(TableRowAlign.CENTER);XWPFTableRow headerRow = table.getRow(0);headerRow.getCell(0).setText("施工单位");headerRow.addNewTableCell().setText("工程项目");headerRow.addNewTableCell().setText("施工项目");headerRow.addNewTableCell().setText("单位");headerRow.addNewTableCell().setText("计划工程量");headerRow.addNewTableCell().setText("");headerRow.addNewTableCell().setText("累计完成量");headerRow.addNewTableCell().setText("");headerRow.addNewTableCell().setText("");headerRow.addNewTableCell().setText("完成比例");headerRow.addNewTableCell().setText("");headerRow.getCell(0).setWidth("600");headerRow.getCell(1).setWidth("600");headerRow.getCell(2).setWidth("600");headerRow.getCell(3).setWidth("600");headerRow.getCell(4).setWidth("600");headerRow.getCell(5).setWidth("600");headerRow.getCell(6).setWidth("600");headerRow.getCell(7).setWidth("600");headerRow.getCell(8).setWidth("600");headerRow.getCell(9).setWidth("600");headerRow.getCell(10).setWidth("600");// 创建表头的第二行XWPFTableRow headerRowTwo = table.createRow();headerRowTwo.getCell(4).setText("年计划");headerRowTwo.getCell(5).setText("月计划");headerRowTwo.getCell(6).setText("日完成量");headerRowTwo.getCell(7).setText("月完成量");headerRowTwo.getCell(8).setText("年完成量");headerRowTwo.getCell(9).setText("月度比例");headerRowTwo.getCell(10).setText("设计比例");headerRowTwo.getCell(0).setWidth("600");headerRowTwo.getCell(1).setWidth("600");headerRowTwo.getCell(2).setWidth("600");headerRowTwo.getCell(3).setWidth("600");headerRowTwo.getCell(4).setWidth("600");headerRowTwo.getCell(5).setWidth("600");headerRowTwo.getCell(6).setWidth("600");headerRowTwo.getCell(7).setWidth("600");headerRowTwo.getCell(8).setWidth("600");headerRowTwo.getCell(9).setWidth("600");headerRowTwo.getCell(10).setWidth("600");// 合并单元格this.fileMergeDay(table);//填入数据List<Map<String, Object>> attach = rateSunJlService.listInfSunAttachAll(time, ids);Map<String, List<Map<String, Object>>> groupedByTenantId = attach.stream().collect(Collectors.groupingBy(map -> map.get("simpleName").toString()));for (String simpleName : groupedByTenantId.keySet()) {List<Map<String, Object>> attachList = groupedByTenantId.get(simpleName);for (int i = 0; i < attachList.size(); i++) {XWPFTableRow dataRow = table.createRow();dataRow.getCell(0).setText(attach.get(i).get("simpleName").toString());dataRow.getCell(1).setText(attach.get(i).get("name").toString());dataRow.getCell(2).setText(attach.get(i).get("item") == null ? "" : attach.get(i).get("item").toString());dataRow.getCell(3).setText(attach.get(i).get("unit") == null ? "" : attach.get(i).get("unit").toString());dataRow.getCell(4).setText(attach.get(i).get("planMeasure") == null ? "" : attach.get(i).get("planMeasure").toString());dataRow.getCell(5).setText(attach.get(i).get("monthMeasure") == null ? "" : attach.get(i).get("monthMeasure").toString());dataRow.getCell(6).setText(attach.get(i).get("dayMeasure") == null ? "" : attach.get(i).get("dayMeasure").toString());dataRow.getCell(7).setText(attach.get(i).get("thisMonthQuantities") == null ? "" : attach.get(i).get("thisMonthQuantities").toString());dataRow.getCell(8).setText(attach.get(i).get("intactMeasure") == null ? "" : attach.get(i).get("intactMeasure").toString());dataRow.getCell(9).setText(attach.get(i).get("thisMonthScale") == null ? "" : attach.get(i).get("thisMonthScale").toString() + "%");dataRow.getCell(10).setText(attach.get(i).get("intactScale") == null ? "" : attach.get(i).get("intactScale").toString() + "%");dataRow.getCell(0).setWidth("600");dataRow.getCell(1).setWidth("600");dataRow.getCell(2).setWidth("600");dataRow.getCell(3).setWidth("600");dataRow.getCell(4).setWidth("600");dataRow.getCell(5).setWidth("600");dataRow.getCell(6).setWidth("600");dataRow.getCell(7).setWidth("600");dataRow.getCell(8).setWidth("600");dataRow.getCell(9).setWidth("600");dataRow.getCell(10).setWidth("600");}fileMergeDayH(table, rowsNum, attachList.size());rowsNum = rowsNum + attachList.size();}//设置表格居中对齐for (XWPFTableRow row : table.getRows()) {// 遍历每一行中的每个单元格for (XWPFTableCell cell : row.getTableCells()) {// 获取单元格的CTTc对象,用于设置对齐方式CTTc cttc = cell.getCTTc();CTTcPr ctTcPr = cttc.isSetTcPr() ? cttc.getTcPr() : cttc.addNewTcPr();// 设置垂直居中ctTcPr.addNewVAlign().setVal(STVerticalJc.CENTER);// 获取单元格中的段落XWPFParagraph paragraph = cell.getParagraphs().get(0);// 设置段落水平居中paragraph.setAlignment(ParagraphAlignment.CENTER);}}FileOutputStream out1 = new FileOutputStream(path);doc.write(out1);out1.close();doc.close();
涵盖的方法:
public void fileMergeDayH(XWPFTable table, int startRows, int length) {for (int i = 1; i < length + 1; i++) {if (i == 1) {table.getRow(startRows + i).getCell(0).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);} else {table.getRow(startRows + i).getCell(0).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);}}table.setTableAlignment(TableRowAlign.CENTER);}public void fileMergeDay(XWPFTable table) {//进行表头合并//横向合并,第一行的8-10table.getRow(0).getCell(4).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);table.getRow(0).getCell(5).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);table.getRow(0).getCell(4).getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf((600 * 1)));table.getRow(0).getCell(6).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);table.getRow(0).getCell(7).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);table.getRow(0).getCell(8).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);table.getRow(0).getCell(6).getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf((600 * 1)));table.getRow(0).getCell(9).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);table.getRow(0).getCell(10).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);table.getRow(0).getCell(9).getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf((600 * 1)));//竖向合并table.getRow(0).getCell(0).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);table.getRow(1).getCell(0).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);table.getRow(0).getCell(1).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);table.getRow(1).getCell(1).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);table.getRow(0).getCell(2).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);table.getRow(1).getCell(2).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);table.getRow(0).getCell(3).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);table.getRow(1).getCell(3).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);table.setTableAlignment(TableRowAlign.CENTER);}
附带转成pdf方法以及以流的形式导出
//将word文件转成pdfString pdfPath = file.getPath().substring(0, file.getPath().indexOf(".docx")) + ".pdf";File pdf = new File(pdfPath);ToPDFUtils.trans(path, pdfPath, ".docx");//将文件以文件流的形式传输InputStream inputStream = null;OutputStream outputStream = null;response.setContentType("application/json;charset=utf-8");// 设置强制下载不打开response.addHeader("Content-Disposition", "attachment;fileName=" + new String(pdf.getPath().getBytes("UTF-8"), "iso-8859-1"));inputStream = new BufferedInputStream(new FileInputStream(pdf.getPath()));outputStream = response.getOutputStream();byte[] buf = new byte[1024];int len;while ((len = inputStream.read(buf)) > 0) {outputStream.write(buf, 0, len);}response.flushBuffer();
package org.jeecg.modules.util;import com.aspose.cells.Font;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;import java.awt.image.BufferedImage;
import java.io.*;
import com.aspose.cells.*;
import org.aspectj.weaver.ast.Test;
import org.springframework.beans.factory.annotation.Value;import javax.imageio.ImageIO;
import java.awt.geom.Dimension2D;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;public class ToPDFUtils {private static List<String> list = new ArrayList<>();private static List<String> dellist = new ArrayList<>();public static String trans(String filePath, String pdfPath, String type) {try {toPdf(filePath, pdfPath, type);} catch (Exception e) {e.printStackTrace();}return pdfPath;}//转换private static void toPdf(String filePath, String pdfPath, String type) {if (".docx".equals(type) || ".doc".equals(type)) {word2PDF(filePath, pdfPath);}else if(".xls".equals(type) || ".xlsx".equals(type)){excel2PDF(filePath,pdfPath);} else if (".ppt".equals(type)) {ppt2PDF(filePath, pdfPath);}else{convert(filePath,pdfPath);}}private static void word2PDF(String inputFile, String pdfFile) {if (!getLicense()) {// 验证License 若不验证则转化出的pdf文档会有水印产生return;}try {long old = System.currentTimeMillis();File file = new File(pdfFile); //新建一个空白pdf文档FileOutputStream os = new FileOutputStream(file);com.aspose.words.Document doc = new com.aspose.words.Document(inputFile); //sourcerFile是将要被转化的word文档doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换os.close();long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时} catch (Exception e) {e.printStackTrace();}}/*** 获取license** @return*/public static boolean getLicense() {boolean result = false;try {InputStream is = Test.class.getClassLoader().getResourceAsStream("\\license.xml");License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}public static void excel2PDF(String excelPath, String pdfPath) {long old = System.currentTimeMillis();// 验证Licenseif (!getLicense()) {return;}FileInputStream fileInputStream = null;FileOutputStream fileOutputStream = null;try {File excelFile = new File(excelPath);if (excelFile.exists()) {fileInputStream = new FileInputStream(excelFile);Workbook workbook = new Workbook(fileInputStream);Worksheet sheet = workbook.getWorksheets().get(0);sheet.getPageSetup().setPrintGridlines(true);File pdfFile = new File(pdfPath);PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();pdfSaveOptions.setOnePagePerSheet(true);//把内容放在一张PDF 页面上;//pdfSaveOptions.setOnePagePerSheet(false);//把内容放在一张PDF 页面上;FileOutputStream fileOS = new FileOutputStream(pdfFile);workbook.save(fileOS, pdfSaveOptions);// 只放一张纸;我的专为横向了long now = System.currentTimeMillis();} else {System.out.println("文件不存在");}} catch (Exception e) {e.printStackTrace();} finally {if (fileInputStream != null) {try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}if (fileOutputStream != null) {try {fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}}}//图片转pdfpublic static void convert(String imagePath, String pdfPath) {try {BufferedImage img = ImageIO.read(new File(imagePath));FileOutputStream fos = new FileOutputStream(pdfPath);Document doc = new Document(null, 0, 0, 0, 0);doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));Image image = Image.getInstance(imagePath);PdfWriter.getInstance(doc, fos);doc.open();doc.add(image);doc.close();} catch (IOException e) {e.printStackTrace();} catch (BadElementException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();}}private static void ppt2PDF(String inputFile, String pdfFile) {ActiveXComponent app = new ActiveXComponent("PowerPoint.Application");try {Dispatch ppts = app.getProperty("Presentations").toDispatch();Dispatch ppt = Dispatch.call(ppts, "Open", new Object[]{inputFile, true, true, false}).toDispatch();Dispatch.call(ppt, "SaveAs", new Object[]{pdfFile, 32});Dispatch.call(ppt, "Close");app.invoke("Quit");} catch (Exception e) {e.printStackTrace();System.out.println("转换出错:" + inputFile);} finally {app.invoke("Quit");}}public static void delFile(List<String> filePaths) {for (String str : filePaths) {try {String filePath = str;filePath = filePath.toString();java.io.File myDelFile = new java.io.File(filePath);myDelFile.delete();} catch (Exception e) {System.out.println(str + "删除文件操作出错");e.printStackTrace();}}}// public static void setPageStyle(String savepath) {
//
// //创建PdfDocument实例
// PdfDocument originalDoc = new PdfDocument();
// //加载PDF文件
// originalDoc.loadFromFile(savepath);
//
// //创建一个新的PdfDocument实例
// PdfDocument newDoc = new PdfDocument();
// newDoc.getPages().add();
// //遍历所有PDF 页面
// //Dimension2D dimension2D = new Dimension();
//
// for (int i = 0; i < originalDoc.getPages().getCount(); i++) {
// PdfPageBase page = originalDoc.getPages().get(i);
// //获取页面旋转角度
// //int rotateAngle = page.getRotation().getValue();
// //判断pdf的纸张方向
// if ((page.getSize().getHeight()) < (page.getSize().getWidth())) {
// //旋转页面270度
// page.setRotation((PdfPageRotateAngle.fromValue(PdfPageRotateAngle.Rotate_Angle_270.getValue())));
//
// //设置新文档页边距为10
// PdfMargins margins = new PdfMargins(10);
// //设置新文档页面大小为A4
// PdfPageBase newPage = newDoc.getPages().add(PdfPageSize.A4, margins);
// //调整画布,设置内容也根据页面的大小进行缩放
// double wScale = (PdfPageSize.A4.getWidth() - 20) / page.getSize().getHeight();
// double hScale = (PdfPageSize.A4.getHeight() - 20) / page.getSize().getWidth();
// newPage.getCanvas().scaleTransform(wScale, hScale);
// //复制原文档的内容到新文档
// newPage.getCanvas().drawTemplate(page.createTemplate(), new Point2D.Float());
// } else {
// //设置新文档页边距为10
// PdfMargins margins = new PdfMargins(10);
// //设置新文档页面大小为A4
// PdfPageBase newPage = newDoc.getPages().add(PdfPageSize.A4, margins);
// //调整画布,设置内容也根据页面的大小进行缩放
// double wScale = (PdfPageSize.A4.getWidth() - 20) / page.getSize().getWidth();
// double hScale = (PdfPageSize.A4.getHeight() - 20) / page.getSize().getHeight();
// newPage.getCanvas().scaleTransform(wScale, hScale);
// //复制原文档的内容到新文档
// newPage.getCanvas().drawTemplate(page.createTemplate(), new Point2D.Float());
// }
//
// }
// //保存PDF
// newDoc.saveToFile(savepath);
// newDoc.getPages().remove(newDoc.getPages().get(0));
// newDoc.saveToFile(savepath);
//
// PdfDocument pdf = newDoc;
// pdf.getPages().add();
// //创建字体
// PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("宋体", Font.PLAIN, 10), true);
//
// //遍历文档中的页
// for (int i = 0; i < pdf.getPages().getCount(); i++) {
// Dimension2D pageSize = pdf.getPages().get(i).getSize();
// float y = (float) pageSize.getHeight() - 40;
// //初始化页码域
// PdfPageNumberField number = new PdfPageNumberField();
//
// //初始化总页数域
// PdfPageCountField count = new PdfPageCountField();
//
// //创建复合域
// PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.getBlack(), "第{0}页 共{1}页", number, count);
//
// //设置复合域内文字对齐方式
// compositeField.setStringFormat(new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top));
//
// //测量文字大小
// Dimension2D textSize = font.measureString(compositeField.getText());
//
// //设置复合域的在PDF页面上的位置及大小
// compositeField.setBounds(new Rectangle2D.Float(((float) pageSize.getWidth() - (float) textSize.getWidth()) / 2, y, (float) textSize.getWidth(), (float) textSize.getHeight()));
//
// //将复合域添加到PDF页面
// compositeField.draw(pdf.getPages().get(i).getCanvas());
// }
// //移除第一个页
// pdf.getPages().remove(pdf.getPages().get(pdf.getPages().getCount() - 1));
// //保存为另外一个文档
// pdf.saveToFile(savepath);
// }// public static boolean mergePdfFiles(String[] files, String newfile) {
// boolean retValue = false;
// Document document = null;
// try {
// document = new Document(new PdfReader(files[0]).getPageSize(1));
// PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
// document.open();
// for (int i = 0; i < files.length; i++) {
// PdfReader reader = new PdfReader(files[i]);
// int n = reader.getNumberOfPages();
// for (int j = 1; j <= n; j++) {
// document.newPage();
// PdfImportedPage page = copy.getImportedPage(reader, j);
// copy.addPage(page);
// }
// }
// retValue = true;
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// document.close();
// }
// return retValue;
// }}