啰嗦两句吧,之前一直用jxl进行导入导出,但人家不更新了,也不能导出成word和PDF格式,网上说主流的下载都是POI了,我没用过这神器,手痒,就写了借鉴一些前辈们的代码写了如下的代码,但在导出Excel设置样式上,因依赖版本是对于今天来说是最新的版本,网上找到的代码写法已经不支持了,就趁着昨晚试着写了写demo,今天早上记录下来吧,大伙一起探讨。下面直接干货: 我用的springboot哦
第一步:pom.xml中加入依赖包:
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
直接干货:上代码------看好注释说明哦
package com.ymw.controller.index;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.ymw.common.base.BaseController;
import com.ymw.controller.HomeController;
import com.ymw.service.records.TradeLineService;
import com.ymw.service.user.GeneralAccountService;
import io.swagger.annotations.Api;
/**
*
* @author: wy
* @创建日期: 2019年12月12日 上午11:05:59
* @ClassName PoiController
* @类描述-Description: TODO(这里用一句话描述这个方法的作用)
* @版本: 1.0
*/
@CrossOrigin
@RestController
@RequestMapping("poi")
@Api(value = "poi")
public class PoiController extends BaseController{
private static Logger logger=LoggerFactory.getLogger(HomeController.class);
@Autowired
private TradeLineService tradeLineService;
@Autowired
private GeneralAccountService generalAccountService;
//固定下载某一个文件夹时候的地址
public static String File_Path = "D:/";
/**
*
* @Description: 生成Excel表格
* @param request 固定下载D盘时候的地址
* @param response
* @throws Exception 參數描述
* @return void 返回类型
* @throws
*/
@GetMapping("excel1")
public static void excel1() throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook(); // 创建Excel表格的
HSSFSheet sheet = workbook.createSheet("新建表11");// 创建工作表sheet
HSSFRow row = sheet.createRow(0); // 在建立的excel中创建一行
HSSFCell cell = row.createCell(0); // 创建该行的对应列
cell.setCellValue("姓名"); // 向该行该列中设置内容
FileOutputStream outputStream = new FileOutputStream(File_Path + "Excel.xls"); // 保存文件的路径
workbook.write(outputStream); // 保存Excel文件
outputStream.close(); // 关闭文件流
System.out.println("excel生成成功!");
}
/**
* 生成Excel表格--页面自定义下载地址和名称
* 表头样式
* @throws Exception
*/
@GetMapping("excel")
public static void excel(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("application/msexcel");
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("模板导出.xls", "UTF-8"));
response.setCharacterEncoding("utf-8");
ServletOutputStream out = response.getOutputStream();
HSSFWorkbook workbook = new HSSFWorkbook(); // 创建Excel表格的
HSSFSheet sheet = workbook.createSheet("新建表");// 创建工作表sheet
HSSFCellStyle style = workbook.createCellStyle();
//一、设置背景色:HSSFCellStyle.LEAST_DOTS
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(IndexedColors.SEA_GREEN.getIndex());
//二、设置边框:
style.setBorderBottom(BorderStyle.THIN); //下边框
style.setBorderLeft(BorderStyle.THIN);//左边框
style.setBorderTop(BorderStyle.THIN);//上边框
style.setBorderRight(BorderStyle.THIN);//右边框
//三、设置居中:
style.setAlignment(HorizontalAlignment.CENTER);
//四、设置字体:
HSSFFont font = workbook.createFont();
font.setFontName("黑体");
font.setFontHeightInPoints((short) 12);//设置字体大小
HSSFFont font2 = workbook.createFont();
font2.setFontName("仿宋_GB2312");
font2.setBold(true);;//粗体显示
font2.setFontHeightInPoints((short) 12);
style.setFont(font);//选择需要用到的字体格式
//五、设置列宽:
// 设置默认列宽,width为字符个数
// sheet.setDefaultColumnWidth(3766);
// sheet.setColumnWidth(0, 3766); //第一个参数代表列id(从0开始),第2个参数代表宽度值
sheet.setColumnWidth(6, 4500); //第一个参数代表列id(从0开始),第2个参数代表宽度值
//六、设置自动换行:
style.setWrapText(true);//设置自动换行
HSSFRow row = sheet.createRow(0); // 在建立的excel中创建一行
HSSFCell cell0 = row.createCell(0); // 创建该行的对应列
cell0.setCellStyle(style);
HSSFCell cell1 = row.createCell(1);
cell1.setCellStyle(style);// 创建该行的对应列
HSSFCell cell2 = row.createCell(2);
cell2.setCellStyle(style);// 创建该行的对应列
HSSFCell cell3 = row.createCell(3);
cell3.setCellStyle(style);
HSSFCell cell4 = row.createCell(4);
cell4.setCellStyle(style);
HSSFCell cell5 = row.createCell(5);
cell5.setCellStyle(style);
HSSFCell cell6 = row.createCell(6);
cell6.setCellStyle(style);
cell0.setCellValue("姓名"); // 向该行该列中设置内容
cell1.setCellValue("性别");
cell2.setCellValue("年龄");
cell3.setCellValue("电话");
cell4.setCellValue("学校");
cell5.setCellValue("班级");
cell6.setCellValue("身份证");
workbook.write(out); // 保存Excel文件
workbook.close();
System.out.println("excel生成成功!");
}
/**
* 生成word文档-----固定下载D盘时候的地址
* @throws Exception
*/
@GetMapping("word1")
public static void word1() throws Exception{
XWPFDocument doc = new XWPFDocument(); //创建word文件
XWPFParagraph p1 = doc.createParagraph(); //创建段落
XWPFRun r1 = p1.createRun(); //创建段落文本
r1.setText("Helloworld"); //设置文本
r1.addBreak(); // 换行
r1.setText("世界你好!");
// TODO 其他操作请自己百度
FileOutputStream outputStream = new FileOutputStream(File_Path + "Word.docx"); // 保存文件的路径
doc.write(outputStream); // 保存Excel文件
outputStream.close(); // 关闭文件流
System.out.println("word--1生成成功!");
}
/**
* 生成word文档-----页面自定义下载地址和名称
* @throws Exception
*/
@GetMapping("word2")
public static void word2(HttpServletRequest request, HttpServletResponse response) throws Exception{
response.setContentType("application/msexcel");
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("模板导出.docx", "UTF-8"));
response.setCharacterEncoding("utf-8");
ServletOutputStream out = response.getOutputStream();
XWPFDocument doc = new XWPFDocument(); //创建word文件
XWPFParagraph p1 = doc.createParagraph(); //创建段落
XWPFRun r1 = p1.createRun(); //创建段落文本
r1.setText("Helloworld"); //设置文本
r1.addBreak(); // 换行
r1.setText("世界你好!gagagagagagagag");
doc.write(out); // 保存word文件
doc.close();
System.out.println("word2生成成功!");
}
/**
* 生成PDF------固定下载D盘时候的地址
* @throws Exception
*/
@GetMapping("pdf1")
public static void createPDF() throws Exception {
// 第一步,实例化一个document对象
Document document = new Document();
// 第二步,设置要到出的路径
FileOutputStream out = new FileOutputStream("D:/workbook111.pdf");
// 如果是浏览器通过request请求需要在浏览器中输出则使用下面方式
// OutputStream out = response.getOutputStream();
// 第三步,设置字符
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
Font fontZH = new Font(bfChinese, 12.0F, 0);
// 第四步,将pdf文件输出到磁盘
PdfWriter writer = PdfWriter.getInstance(document, out);
// 第五步,打开生成的pdf文件
document.open();
// 第六步,设置内容
String title = "标题";
document.add(new Paragraph(new Chunk(title, fontZH).setLocalDestination(title)));
document.add(new Paragraph("\n"));
// 创建table,注意这里的2是两列的意思,下面通过table.addCell添加的时候必须添加整行内容的所有列
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100.0F);
table.setHeaderRows(1);
table.getDefaultCell().setHorizontalAlignment(1);
table.addCell(new Paragraph("序号", fontZH));
table.addCell(new Paragraph("结果", fontZH));
table.addCell(new Paragraph("1", fontZH));
table.addCell(new Paragraph("出来了", fontZH));
document.add(table);
document.add(new Paragraph("\n"));
// 第七步,关闭document
document.close();
System.out.println("导出pdf成功~");
}
/**
* 生成PDF------前端自定义下载地址
* @throws Exception
*/
@GetMapping("pdf2")
public static void pdf2(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 第一步,实例化一个document对象
Document document = new Document();
// 第二步,设置要到出的路径
// FileOutputStream out = new FileOutputStream("D:/workbook111.pdf");
response.setContentType("application/msexcel");
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("模板导出.pdf", "UTF-8"));
response.setCharacterEncoding("utf-8");
ServletOutputStream out = response.getOutputStream();
// 如果是浏览器通过request请求需要在浏览器中输出则使用下面方式
// OutputStream out = response.getOutputStream();
// 第三步,设置字符
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
Font fontZH = new Font(bfChinese, 12.0F, 0);
// 第四步,将pdf文件输出到磁盘
PdfWriter writer = PdfWriter.getInstance(document, out);
// 第五步,打开生成的pdf文件
document.open();
// 第六步,设置内容
String title = "标题";
document.add(new Paragraph(new Chunk(title, fontZH).setLocalDestination(title)));
document.add(new Paragraph("\n"));
// 创建table,注意这里的2是两列的意思,下面通过table.addCell添加的时候必须添加整行内容的所有列
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100.0F);
table.setHeaderRows(1);
table.getDefaultCell().setHorizontalAlignment(1);
table.addCell(new Paragraph("序号", fontZH));
table.addCell(new Paragraph("结果", fontZH));
table.addCell(new Paragraph("1", fontZH));
table.addCell(new Paragraph("出来了", fontZH));
document.add(table);
document.add(new Paragraph("\n"));
// 第七步,关闭document
document.close();
System.out.println("导出pdf成功~");
}
}