POI 导出横版A4word,并设置excel宽度(固定不变形)

1.maven依赖

<!-- 导出EXCEL -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <!-- 导出EXCEL -->
        <!-- word读取 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>ooxml-schemas</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- word读取 -->

二导出word 横版:3要点

  1. ooxml-schemas 依赖
       <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>ooxml-schemas</artifactId>
            <version>1.4</version>
        </dependency>
  1. 设置 :横屏板式
XWPFDocument 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();
        }
        //1. 设置页面大小  当前A4大小
        CTPageSz pageSize = section.getPgSz();
        //1.1 必须要设置下面两个参数,否则整个的代码是无效的
        pageSize.setW(BigInteger.valueOf(16840));
        pageSize.setH(BigInteger.valueOf(11907));
        pageSize.setOrient(STPageOrientation.LANDSCAPE);

3.设置excel表格布局方式

		//4 表格内容
        XWPFTable comTable = doc.createTable();
        //4.1表格宽度为指定宽度:STTblWidth.DXA 1
        CTTblPr ctTblPr = comTable.getCTTbl().addNewTblPr();
        CTTblWidth comTableWidth = ctTblPr.addNewTblW();
        comTableWidth.setType(STTblWidth.DXA);
        comTableWidth.setW(BigInteger.valueOf(16000));

        //4.1.2设置布局为固定不便方式
        CTTblLayoutType ctTblLayoutType = ctTblPr.isSetTblLayout()?ctTblPr.getTblLayout():ctTblPr.addNewTblLayout();
        ctTblLayoutType.setType(STTblLayoutType.FIXED);

网络通用下下载横版word 横版excel 表格:

import org.apache.commons.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;


import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ExportWord {


    /**
     * 下载横屏word的excel表格
     *
     * @param filename:文件名
     * @param titleStr:标题名
     * @param description:居中描述:可空
     * @param value_columns:列明
     * @param dataList:数据
     * @param colWidths:列宽度,可空
     * @param response:HttpServletResponse
     * @throws IOException
     */
    public static void downWordTransverse(String filename, String titleStr, String description, String[] value_columns, List<List<String>> dataList, Integer[] colWidths,ParagraphAlignment[] excelAlign, HttpServletResponse response) throws IOException {

        XWPFDocument 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();
        }
        //1. 设置页面大小  当前A4大小
        CTPageSz pageSize = section.getPgSz();
        //1.1 必须要设置下面两个参数,否则整个的代码是无效的
        pageSize.setW(BigInteger.valueOf(16840));
        pageSize.setH(BigInteger.valueOf(11907));
        pageSize.setOrient(STPageOrientation.LANDSCAPE);
        //1.2 设置页面为窄边距
        setDocumentMargin(section,"420","720","420","720");

        //2. 添加标题
        XWPFParagraph titleParagraph = doc.createParagraph();
        //设置段落居中
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun titleParagraphRun = titleParagraph.createRun();
        titleParagraphRun.setText(titleStr);
        titleParagraphRun.setColor("000000");
        titleParagraphRun.setFontFamily("方正小标宋简体");
        titleParagraphRun.setFontSize(22);

        if (!StringUtils.isEmpty(description)) {
            //3. 添加段落,描述
            XWPFParagraph dateParagraph = doc.createParagraph();
            //3.1 设置段落居中
            dateParagraph.setAlignment(ParagraphAlignment.CENTER);

            //3.2设置标题居中
            XWPFRun dateParagraphRun = dateParagraph.createRun();
            dateParagraphRun.setText(description);
            dateParagraphRun.setColor("000000");
            dateParagraphRun.setFontFamily("仿宋");
            dateParagraphRun.setFontSize(12);
        }

        //4.表格
        //表格内容
        XWPFTableCell cell;
        CTTcPr cellPr;
        CTTblWidth cellw;
        XWPFTable comTable = doc.createTable();
        //4.1表格宽度为指定宽度:STTblWidth.DXA 1
        CTTblPr ctTblPr = comTable.getCTTbl().addNewTblPr();
        CTTblWidth comTableWidth = ctTblPr.addNewTblW();
        comTableWidth.setType(STTblWidth.DXA);
        comTableWidth.setW(BigInteger.valueOf(16000));

        //4.1.2设置布局为固定不便方式
        CTTblLayoutType ctTblLayoutType = ctTblPr.isSetTblLayout()?ctTblPr.getTblLayout():ctTblPr.addNewTblLayout();
        ctTblLayoutType.setType(STTblLayoutType.FIXED);

        //4.2 表头
        XWPFTableRow rowHead = comTable.getRow(0);

        //4.3设置表格首行单元格
        XWPFParagraph cellParagraph;
        XWPFRun cellParagraphRun;
        for (int i = 0; i < value_columns.length; i++) {

            if(i==0){
                cell = rowHead.getCell(0);
            }else{
                cell = rowHead.addNewTableCell();
            }
            cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);//垂直居中
            //设置单元格宽度
            cellPr = cell.getCTTc().addNewTcPr();
            cellw = cellPr.addNewTcW();
            if(colWidths!=null){
                cellw.setType(STTblWidth.DXA);
                cellw.setW(BigInteger.valueOf(colWidths[i]));
            }

            //设置单元格内容
            cellParagraph = cell.getParagraphs().get(0);
            cellParagraph.setAlignment(ParagraphAlignment.CENTER); //设置表头单元格居中
            cellParagraphRun = cellParagraph.createRun();

            cellParagraphRun.setFontFamily("黑体");
            cellParagraphRun.setFontSize(12); //设置表头单元格居中
            cellParagraphRun.setText(value_columns[i]);
        }

        int rows = dataList.size();

        for (int i = 0; i < rows; i++) {
            XWPFTableRow rowsContent = comTable.createRow();
            for (int j = 0; j < dataList.get(i).size(); j++) {

                //设置单元格宽度
                cell = rowsContent.getCell(j);
                cellPr = cell.getCTTc().addNewTcPr();
                cellw = cellPr.addNewTcW();
                if(colWidths!=null){
                    cellw.setType(STTblWidth.DXA);
                    cellw.setW(BigInteger.valueOf(colWidths[j]));
                }
                cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);//垂直居中
                //设置单元格内容
                XWPFParagraph cellParagraphC = cell.getParagraphs().get(0);
                if(excelAlign!=null){
                    cellParagraphC.setAlignment(excelAlign[j]);
                }else{
                    cellParagraphC.setAlignment(ParagraphAlignment.LEFT);
                }


                String textContent = dataList.get(i).get(j);
                if (textContent.indexOf("\n") == -1) {
                    XWPFRun cellParagraphRunC = cellParagraphC.createRun();
                    cellParagraphRunC.setFontFamily("仿宋");
                    cellParagraphRunC.setFontSize(12); //设置表格内容字号
                    cellParagraphRunC.setText(dataList.get(i).get(j) + ""); //单元格段落加载内容
                } else {
                    String[] textContentArray = textContent.split("\n");
                    int m = 0;
                    for (String text : textContentArray) {
                        String regex = "^\\*\\*(.*?)\\*\\*";
                        Pattern pattern = Pattern.compile(regex);
                        Matcher matcher = pattern.matcher(text);
                        if(matcher.find()){
                            String contentF = matcher.group().replaceAll("\\*","");
                            XWPFRun cellParagraphRunC = cellParagraphC.createRun();
                            cellParagraphRunC.setFontFamily("仿宋");
                            cellParagraphRunC.setFontSize(12); //设置表格内容字号
                            cellParagraphRunC.setText(contentF);//设置该段内容
                            cellParagraphRunC.setBold(true);//设置加粗

                            //取出剩余的内容
                            text = text.replace(matcher.group(),"");
                        }

                        m++;
                        XWPFRun cellParagraphRunC = cellParagraphC.createRun();
                        cellParagraphRunC.setFontFamily("仿宋");
                        cellParagraphRunC.setFontSize(12); //设置表格内容字号
                        cellParagraphRunC.setText(text);
                        if(m!=textContentArray.length){
                            cellParagraphRunC.addBreak(BreakType.TEXT_WRAPPING);
                        }
                    }
                }
            }
        }

        OutputStream out = null;
        try {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "utf-8") + ".docx");// 设置文件名
            out = response.getOutputStream();
            doc.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置页边距 (word中1厘米约等于567)
     * @param section
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    public static void setDocumentMargin(CTSectPr section, String left,String top, String right, String bottom) {
        if(!section.isSetPgMar()){
            section.addNewPgMar();
        }
        CTPageMar ctpagemar = section.getPgMar();
        if (!Util.isNull(left)) {
            ctpagemar.setLeft(new BigInteger(left));
        }
        if (!Util.isNull(top)) {
            ctpagemar.setTop(new BigInteger(top));
        }
        if (!Util.isNull(right)) {
            ctpagemar.setRight(new BigInteger(right));
        }
        if (!Util.isNull(bottom)) {
            ctpagemar.setBottom(new BigInteger(bottom));
        }
    }
}

三、工具类使用方式及效果

String titleStr = "标题";
String description = "描述";
String[] value_columns = {"列1", "列2", "列3","列4","列5","列6","列7","列8"};
List<List<String>> dataList = new ArrayList<>();//导出的数据
Integer[] colWidths = {600,1700,2200,700,900,1500,7350,1050};//导出的excel宽度excel(扣除边距剩余共16000宽)
ParagraphAlignment[] excelAlign = {ParagraphAlignment.CENTER,ParagraphAlignment.LEFT,ParagraphAlignment.LEFT,ParagraphAlignment.CENTER
		,ParagraphAlignment.CENTER,ParagraphAlignment.LEFT,ParagraphAlignment.LEFT,ParagraphAlignment.CENTER};//设置水平方向
		
downWordTransverse(titleStr,titleStr,description,value_columns,dataList,colWidths,excelAlign,response);

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_26408545/article/details/110669104