注意:POI包的版本,不同版本poi导出API会有差别!!!!
org.apache.poi
poi
4.1.2
org.apache.poi
poi-ooxml
4.1.2
工具类
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
工具类
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