POi 导出word 表格,设置页面横版

https://blog.csdn.net/qq_26408545/article/details/110669104

poi 导入,高版本不兼容,建议以下版本:

<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>
<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>

jdk:1.8

自己的例子:

public void wordExportOut(HttpServletResponse response){
        int row = 10;
        int column = 10;
        //新建一个文档
        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();
        }
        CTPageSz pageSize = section.getPgSz();
        //必须要设置下面两个参数,否则整个的代码是无效的
        pageSize.setW(BigInteger.valueOf(15840));
        pageSize.setH(BigInteger.valueOf(12240));
        pageSize.setOrient(STPageOrientation.LANDSCAPE);
        //创建一个表格
        XWPFTable table = doc.createTable(row,column);
        //测试数据
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                table.getRow(i).getCell(j).setText(""+i+":"+j);
            }
        }
        String fileName = "我的.doc";
        //设置相应头
        try {
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            //遵守缓存规定
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        //输出流
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            doc.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

package com.kang.staffinfosystem.util;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.util.StringUtils;


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);
                        }
                    }
                }
            }
        }
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "utf-8") + ".docx");// 设置文件名
        try (OutputStream out = response.getOutputStream();){
            doc.write(out);
        } 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 (!isNull(left)) {
            ctpagemar.setLeft(new BigInteger(left));
        }
        if (!isNull(top)) {
            ctpagemar.setTop(new BigInteger(top));
        }
        if (!isNull(right)) {
            ctpagemar.setRight(new BigInteger(right));
        }
        if (!isNull(bottom)) {
            ctpagemar.setBottom(new BigInteger(bottom));
        }
    }
    public static boolean isNull(Object obj) {
        return obj == null;
    }
}

工具类使用方式

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);

Guess you like

Origin blog.csdn.net/qq_40197728/article/details/120195001