JAVA使用POI导出Word文档和Excel文档

导包
注意:POI包的版本,不同版本poi导出API会有差别!!!!
<dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>4.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.1.2</version>
    </dependency>
导出Excel文件

工具类

import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

public class ExcelUtil {
	public static HSSFWorkbook getWorkbook(){
        return new HSSFWorkbook();
    }
    //设置字体
    public static Font setFont(HSSFWorkbook workbook,String name,short size,boolean isBold){
        HSSFFont font = workbook.createFont();
        font.setFontName(name);
        font.setFontHeightInPoints(size);//设置字体大小
        if(isBold){
            font.setBold(isBold);//加粗
        }
        return font;
    }
    //设置单元格样式
    public static CellStyle setCellStyle(Workbook workbook,Font font){
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//指定单元格居中对齐
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//指定单元格垂直居中对齐
        cellStyle.setWrapText(true);//指定单元格自动换行
        //设置边框
        cellStyle.setBorderTop(BorderStyle.THIN);//上边框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
        cellStyle.setBorderBottom(BorderStyle.THIN);//下边框
        cellStyle.setBorderRight(BorderStyle.THIN);//右边框
        //设置字体
        cellStyle.setFont(font);
        return cellStyle;
    }
    public static void exportFile(HttpServletRequest request, HttpServletResponse response,Workbook wb,String fileName){
        try{
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String agent = request.getHeader("User-Agent");
            boolean isMSIE =((agent!=null&&agent.indexOf("MSIE")!=-1)||(agent!=null&&agent.indexOf("like Gecko")!=-1));
            if(isMSIE){
                response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF8"));
            }else{
                response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
            }
            wb.write(response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

导出示例

 public void exportExcel(){
    HSSFWorkbook hwb =ExcelUtil.getWorkbook();
    HSSFSheet sheet =hwb.createSheet();
    // HSSFSheet sheet = hwb.createSheet("sheetName");//创建sheet,并设置名称
    String[] title = {"标题1","标题2","标题3","标题4"};
    //设置打印方式
    PrintSetup ps =sheet.getPrintSetup();
    ps.setLandscape(false);//纸张方向 true:横向,false:纵向
    ps.setPaperSize(PrintSetup.A4_PAPERSIZE);//纸张--A4
    //设置列宽
    sheet.setColumnWidth(0,5120);
    sheet.setColumnWidth(1,10240);
    sheet.setColumnWidth(2,5120);
    sheet.setColumnWidth(3,5120);
    int rowNum = 0;
    //表头(加粗-居中)
    Font font =ExcelUtil.setFont(hwb,"宋体",(short) 20,true);
    Row row=sheet.createRow(rowNum);
    row.setHeightInPoints(20);//设置行高
    Cell cell = null;
    for (int i = 0;i<title.length;i++){
        cell = row.createCell(i);
        cell.setCellValue(title[i]);//设置内容
        //设置样式
        cell.setCellStyle(ExcelUtil.setCellStyle(hwb,font));
    }
    //第一行数据
    rowNum++;
    row=sheet.createRow(rowNum);
    cell = row.createCell(0);
    cell.setCellValue("合并行");//设置内容
    cell = row.createCell(1);
    cell.setCellValue("合并列");//设置内容
    sheet.addMergedRegion(new CellRangeAddress(rowNum,rowNum,1,3));//合并列 参数(开始行,结束行,开始列,结束列)
    //第二行数据
    rowNum++;
    row=sheet.createRow(rowNum);
    cell = row.createCell(1);
    cell.setCellValue("2-1");//设置内容

    cell = row.createCell(2);
    cell.setCellValue("2-2");//设置内容

    cell = row.createCell(3);
    cell.setCellValue("2-3");//设置内容
    sheet.addMergedRegion(new CellRangeAddress(rowNum-1,rowNum,0,0));//合并行
    ExcelUtil.exportFile(request,response,hwb,"file.xlsx");
}
导出word文件

工具类

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import org.apache.poi.util.Units;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.TextAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPicture;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WordUtil {
	//创建文档对象
	public static XWPFDocument getXWPFDocument(){
		return new XWPFDocument();
	}
	//导出文件
	public static void ExportFile(HttpServletRequest request, HttpServletResponse response, XWPFDocument document, String fileName){
		try {
			response.setContentType("application/msword;charset=utf-8");
			String agent = request.getHeader("User-Agent");
			boolean isMSIE =((agent!=null&&agent.indexOf("MSIE")!=-1)||(agent!=null&&agent.indexOf("like Gecko")!=-1));
			if(isMSIE){
				response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF8"));    
			}else{
				response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("UTF-8"), "ISO8859-1"));    
			}
			document.write( response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//设置页眉
	public static void setHeaderImgAndText(XWPFDocument document,String headerText,String imgPath,
			ParagraphAlignment align,TextAlignment alignH,String font,int size){
		try {
			CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
			XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);

			XWPFHeader header=policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
			XWPFParagraph paragraph=header.createParagraph();
			paragraph.setAlignment(align);
			paragraph.setVerticalAlignment(alignH);

			CTTabStop tabStop=paragraph.getCTP().getPPr().addNewTabs().addNewTab();
			tabStop.setVal(STTabJc.RIGHT);
			//tabStop.setPos(new BigInteger("10800"));

			XWPFRun run = paragraph.createRun();
			setXWPFRunStyle(run,font,size,"",false);
			if(imgPath!=null && !"".equals(imgPath)){
				InputStream is = new FileInputStream(new File(imgPath));
				XWPFPicture picture=run.addPicture(is, XWPFDocument.PICTURE_TYPE_BMP, imgPath, Units.toEMU(200), Units.toEMU(45));
				String blipID="";
				for (XWPFPictureData pictureData : header.getAllPictures()) {
					blipID = header.getRelationId(pictureData);
				}
				picture.getCTPicture().getBlipFill().getBlip().setEmbed(blipID);
				run.addTab();
				is.close();
			}
			if(headerText!=null && !"".equals(headerText)){
				run = paragraph.createRun();
				run.setText(headerText);
				setXWPFRunStyle(run, font, size,"",false);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	//设置字体样式
	public static void setXWPFRunStyle(XWPFRun r1,String font,int size,String color,boolean blod){
		r1.setFontFamily("新宋体");
		r1.setFontSize(10);
		if(color!=null && "".equals(color)){
			r1.setColor(color);
		}
		r1.setBold(blod);
	}
	//跨列合并单元格
	public static void mergeCellHorizotal(XWPFTable table,int row,int beginCell,int endCell){
		for(int cellIndex = beginCell; cellIndex <=endCell;cellIndex++){
			XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
			if(cellIndex==beginCell){
				cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
			}else{
				cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
			}
		}
	}
	//跨行合并单元格
	public static void mergeCellVertically(XWPFTable table,int col,int beginRow,int endRow){
		for(int rowIndex = beginRow; rowIndex <=endRow;rowIndex++){
			XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
			if(rowIndex==beginRow){
				cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
			}else{
				cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
			}
		}
	}
}

导出示例

public void exportWord(){
    XWPFDocument document= WordUtil.getXWPFDocument();
    String path = "E:/yemei.bmp";
    WordUtil.setHeaderImgAndText(document,"页眉",path, ParagraphAlignment.LEFT, TextAlignment.BOTTOM,"宋体",10);

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

    XWPFRun titleParagraphRun = titleParagraph.createRun();
    titleParagraphRun.setText("标题,加粗");
    WordUtil.setXWPFRunStyle(titleParagraphRun, "宋体", 18, "",true);

    //段落
    XWPFParagraph firstParagraph = document.createParagraph();
    XWPFRun run = firstParagraph.createRun();
    run.setText("Java POI 生成word文件。");
    WordUtil.setXWPFRunStyle(run, "宋体", 16, "696969",false);

    //设置段落背景颜色
    CTShd cTShd = run.getCTR().addNewRPr().addNewShd();
    cTShd.setVal(STShd.CLEAR);
    cTShd.setFill("97FFFF");


    //换行
    XWPFParagraph paragraph1 = document.createParagraph();
    XWPFRun paragraphRun1 = paragraph1.createRun();
    paragraphRun1.setText("\r");


    //基本信息表格
    XWPFTable infoTable = document.createTable();
    //去表格边框
    infoTable.getCTTbl().getTblPr().unsetTblBorders();


    //列宽自动分割
    CTTblWidth infoTableWidth = infoTable.getCTTbl().addNewTblPr().addNewTblW();
    infoTableWidth.setType(STTblWidth.DXA);
    infoTableWidth.setW(BigInteger.valueOf(9072));


    //表格第一行
    XWPFTableRow infoTableRowOne = infoTable.getRow(0);
    infoTableRowOne.getCell(0).setText("职位");
    infoTableRowOne.addNewTableCell().setText(": Java 开发工程师");

    //表格第二行
    XWPFTableRow infoTableRowTwo = infoTable.createRow();
    infoTableRowTwo.getCell(0).setText("姓名");
    infoTableRowTwo.getCell(1).setText(": seawater");

    //表格第三行
    XWPFTableRow infoTableRowThree = infoTable.createRow();
    infoTableRowThree.getCell(0).setText("生日");
    infoTableRowThree.getCell(1).setText(": xxx-xx-xx");

    //表格第四行
    XWPFTableRow infoTableRowFour = infoTable.createRow();
    infoTableRowFour.getCell(0).setText("性别");
    infoTableRowFour.getCell(1).setText(": 男");

    //表格第五行
    XWPFTableRow infoTableRowFive = infoTable.createRow();
    infoTableRowFive.getCell(0).setText("现居地");
    infoTableRowFive.getCell(1).setText(": xx");


    //两个表格之间加个换行
    XWPFParagraph paragraph = document.createParagraph();
    XWPFRun paragraphRun = paragraph.createRun();
    paragraphRun.setText("\r");



    //工作经历表格
    XWPFTable ComTable = document.createTable();


    //列宽自动分割
    CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
    comTableWidth.setType(STTblWidth.DXA);
    comTableWidth.setW(BigInteger.valueOf(9072));

    //表格第一行
    XWPFTableRow comTableRowOne = ComTable.getRow(0);
    comTableRowOne.getCell(0).setText("开始时间");
    comTableRowOne.addNewTableCell().setText("结束时间");
    comTableRowOne.addNewTableCell().setText("公司名称");
    comTableRowOne.addNewTableCell().setText("title");

    //表格第二行
    XWPFTableRow comTableRowTwo = ComTable.createRow();
    comTableRowTwo.getCell(0).setText("2016-09-06");
    comTableRowTwo.getCell(1).setText("至今");
    comTableRowTwo.getCell(2).setText("seawater");
    comTableRowTwo.getCell(3).setText("Java开发工程师");

    //表格第三行
    XWPFTableRow comTableRowThree = ComTable.createRow();
    comTableRowOne = ComTable.createRow();
    WordUtil.mergeCellVertically(ComTable,0,2,3);
    comTableRowThree.getCell(0).setText("2016-09-06");
    comTableRowThree.getCell(1).setText("至今");
    comTableRowThree.getCell(2).setText("seawater");
    comTableRowThree.getCell(3).setText("Java开发工程师");

    WordUtil.mergeCellHorizotal(ComTable, 3, 1, 3);
    comTableRowOne.getCell(1).setText("合并单元格");

    WordUtil.ExportFile(request,response, document, "file.docx");
    System.out.println("create_table document written success.");
}

poi导出word比较麻烦,可以参考使用poi-tl模板导出
参考:https://blog.csdn.net/Yao_ban/article/details/108799684?spm=1001.2014.3001.5501

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用JavaPOI导出Excel文件的步骤: 1. 首先,需要在项目中引入POI的依赖,可以通过Maven或手动下载jar包的方式引入。 2. 创建一个工作簿对象,可以通过HSSFWorkbook或XSSFWorkbook类来创建,前者用于创建xls格式的Excel文件,后者用于创建xlsx格式的Excel文件。 3. 创建一个工作表对象,可以通过工作簿对象的createSheet()方法来创建。 4. 创建行和单元格对象,可以通过工作表对象的createRow()和createCell()方法来创建。 5. 设置单元格的值,可以通过单元格对象的setCellValue()方法来设置。 6. 将工作簿对象写入到输出流中,可以通过工作簿对象的write()方法来实现。 以下是一个简单的示例代码,用于将数据导出Excel文件中: ```java import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class ExcelExporter { public static void export() throws IOException { // 创建工作簿对象 Workbook workbook = new HSSFWorkbook(); // 创建工作表对象 Sheet sheet = workbook.createSheet("Sheet1"); // 创建行对象 Row row = sheet.createRow(0); // 创建单元格对象 Cell cell = row.createCell(0); // 设置单元格的值 cell.setCellValue("Hello, World!"); // 将工作簿对象写入到输出流中 FileOutputStream fos = new FileOutputStream("output.xls"); workbook.write(fos); fos.close(); } } ``` 调用export()方法即可将数据导出到名为output.xls的Excel文件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值