700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > JAVA使用POI导出Word文档和Excel文档

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

时间:2022-04-21 18:16:07

相关推荐

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 .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 .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.x.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("-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("-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模板导出

参考:/Yao_ban/article/details/108799684?spm=1001..3001.5501

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。