囉嗦兩句吧,之前一直用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成功~");
}
}