本文以用SpringBoot管理PDF和Excel文件為例,為大家分析用SpringBoot管理文件的具體實現(xiàn)。閱讀完整文相信大家對SpringBoot管理文件的方法有了一定的認(rèn)識。
創(chuàng)新互聯(lián)建站主營玉門網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,重慶App定制開發(fā),玉門h5微信小程序搭建,玉門網(wǎng)站營銷推廣歡迎玉門等地區(qū)企業(yè)咨詢
一、文檔類型簡介
Excel一款電子表格軟件。直觀的界面、出色的計算功能和圖表工具,在系統(tǒng)開發(fā)中,經(jīng)常用來把數(shù)據(jù)轉(zhuǎn)存到Excel文件,或者Excel數(shù)據(jù)導(dǎo)入系統(tǒng)中,這就涉及數(shù)據(jù)轉(zhuǎn)換問題。
PDF是可移植文檔格式,是一種電子文件格式,具有許多其他電子文檔格式無法相比的優(yōu)點。PDF文件格式可以將文字、字型、格式、顏色及獨立于設(shè)備和分辨率的圖形圖像等封裝在一個文件中。該格式文件還可以包含超文本鏈接、聲音和動態(tài)影像等電子信息,支持特長文件,集成度和安全可靠性都較高。
Apache POI是Apache軟件基金會的開源類庫,POI提供API給Java程序?qū)icrosoft Office格式檔案讀和寫的功能。
org.apache.poi
poi
3.9
org.apache.poi
poi-ooxml
3.9
public static List> readExcel(String path) throws Exception {
File file = new File(path) ;
List> list = new LinkedList<>();
XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file));
// 讀取 Sheet1 表格內(nèi)容
XSSFSheet sheet = xwb.getSheetAt(0);
// 讀取行數(shù):不讀取Excel表頭
for (int i = (sheet.getFirstRowNum()+1); i <= (sheet.getPhysicalNumberOfRows()-1); i++) {
XSSFRow row = sheet.getRow(i);
if (row == null) { continue; }
List
public static void createExcel(String excelName, String[] headList,List> dataList)
throws Exception {
// 創(chuàng)建 Excel 工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
// 創(chuàng)建表頭
XSSFRow row = sheet.createRow(0);
for (int i = 0; i < headList.length; i++) {
XSSFCell cell = row.createCell(i);
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
cell.setCellValue(headList[i]);
}
//添加數(shù)據(jù)
for (int line = 0; line < dataList.size(); line++) {
XSSFRow rowData = sheet.createRow(line+1);
List
public static void exportExcel(String[] headList, List> dataList,
OutputStream outputStream) throws Exception {
// 創(chuàng)建 Excel 工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
// 創(chuàng)建表頭
XSSFRow row = sheet.createRow(0);
for (int i = 0; i < headList.length; i++) {
XSSFCell cell = row.createCell(i);
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
cell.setCellValue(headList[i]);
}
//添加數(shù)據(jù)
for (int line = 0; line < dataList.size(); line++) {
XSSFRow rowData = sheet.createRow(line+1);
List
@RestController
public class ExcelWeb {
@RequestMapping("/web/outExcel")
public void outExcel (HttpServletResponse response) throws Exception {
String exportName = "2020-01-user-data" ;
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment;filename="+
URLEncoder.encode(exportName, "UTF-8") + ".xlsx");
List> dataList = ExcelUtil.readExcel("F:\\file-type\\user-excel.xlsx") ;
String[] headList = new String[]{"用戶ID", "用戶名", "手機(jī)號"} ;
ExcelUtil.exportExcel(headList,dataList,response.getOutputStream()) ;
}
}
iText是一種生成PDF報表的Java組件。通過在服務(wù)器端使用頁面或API封裝生成PDF報表,客戶端可以通過超鏈接直接顯示或下載到本地,在系統(tǒng)開發(fā)中通常用來生成比較正式的報告或者合同類的電子文檔。
com.itextpdf
itextpdf
5.5.11
com.itextpdf.tool
xmlworker
5.5.11
首先對于Itext提供的API做一下表格、段落、圖片等基礎(chǔ)樣式的二次封裝,可以更好的適配業(yè)務(wù)。
public class PdfFontUtil {
private PdfFontUtil(){}
/**
* 段落樣式獲取
*/
public static Paragraph getParagraph (String content, Font font,Integer alignment){
Paragraph paragraph = new Paragraph(content,font) ;
if (alignment != null && alignment >= 0){
paragraph.setAlignment(alignment);
}
return paragraph ;
}
/**
* 圖片樣式
*/
public static Image getImage (String imgPath,float width,float height) throws Exception {
Image image = Image.getInstance(imgPath);
image.setAlignment(Image.MIDDLE);
if (width > 0 && height > 0){
image.scaleAbsolute(width, height);
}
return image ;
}
/**
* 表格生成
*/
public static PdfPTable getPdfPTable01 (int numColumns,float totalWidth) throws Exception {
// 表格處理
PdfPTable table = new PdfPTable(numColumns);
// 設(shè)置表格寬度比例為%100
table.setWidthPercentage(100);
// 設(shè)置寬度:寬度平均
table.setTotalWidth(totalWidth);
// 鎖住寬度
table.setLockedWidth(true);
// 設(shè)置表格上面空白寬度
table.setSpacingBefore(10f);
// 設(shè)置表格下面空白寬度
table.setSpacingAfter(10f);
// 設(shè)置表格默認(rèn)為無邊框
table.getDefaultCell().setBorder(0);
table.setPaddingTop(50);
table.setSplitLate(false);
return table ;
}
/**
* 表格內(nèi)容
*/
public static PdfPCell getPdfPCell (Phrase phrase){
return new PdfPCell (phrase) ;
}
/**
* 表格內(nèi)容帶樣式
*/
public static void addTableCell (PdfPTable dataTable,Font font,List cellList){
for (String content:cellList) {
dataTable.addCell(getParagraph(content,font,-1));
}
}
}
這里基于上面的工具類,畫一個PDF頁面作為參考。
public class PdfPage01 {
// 基礎(chǔ)配置
private static String PDF_SITE = "F:\\file-type\\PDF頁面2020-01-15.pdf" ;
private static String FONT = "C:/Windows/Fonts/simhei.ttf";
private static String PAGE_TITLE = "PDF數(shù)據(jù)導(dǎo)出報告" ;
// 基礎(chǔ)樣式
private static Font TITLE_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H,20, Font.BOLD);
private static Font NODE_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H,15, Font.BOLD);
private static Font BLOCK_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H,13, Font.BOLD, BaseColor.BLACK);
private static Font INFO_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H,12, Font.NORMAL,BaseColor.BLACK);
private static Font CONTENT_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
private static void createPdfPage () throws Exception {
// 創(chuàng)建文檔
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDF_SITE));
document.open();
// 報告標(biāo)題
document.add(PdfFontUtil.getParagraph(PAGE_TITLE,TITLE_FONT,1)) ;
document.add(PdfFontUtil.getParagraph("\n商戶名稱:XXX科技有限公司",INFO_FONT,-1)) ;
document.add(PdfFontUtil.getParagraph("\n生成時間:2020-01-15\n\n",INFO_FONT,-1)) ;
// 報告內(nèi)容
// 段落標(biāo)題 + 報表圖
document.add(PdfFontUtil.getParagraph("城市數(shù)據(jù)分布統(tǒng)計",NODE_FONT,-1)) ;
document.add(PdfFontUtil.getParagraph("\n· 可視化圖表\n\n",BLOCK_FONT,-1)) ;
// 設(shè)置圖片寬高
float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
float documentHeight = documentWidth / 580 * 320;
document.add(PdfFontUtil.getImage("F:\\file-type\\myChart.jpg",documentWidth-80,documentHeight-80)) ;
// 數(shù)據(jù)表格
document.add(PdfFontUtil.getParagraph("\n· 數(shù)據(jù)詳情\n\n",BLOCK_FONT,-1)) ;
PdfPTable dataTable = PdfFontUtil.getPdfPTable01(4,400) ;
// 設(shè)置表格
List tableHeadList = tableHead () ;
List> tableDataList = getTableData () ;
PdfFontUtil.addTableCell(dataTable,CONTENT_FONT,tableHeadList);
for (List tableData : tableDataList) {
PdfFontUtil.addTableCell(dataTable,CONTENT_FONT,tableData);
}
document.add(dataTable);
document.add(PdfFontUtil.getParagraph("\n· 報表描述\n\n",BLOCK_FONT,-1)) ;
document.add(PdfFontUtil.getParagraph("數(shù)據(jù)報告可以監(jiān)控每天的推廣情況," +
"可以針對不同的數(shù)據(jù)表現(xiàn)進(jìn)行分析,以提升推廣效果。",CONTENT_FONT,-1)) ;
document.newPage() ;
document.close();
writer.close();
}
private static List> getTableData (){
List> tableDataList = new ArrayList<>() ;
for (int i = 0 ; i < 3 ; i++){
List tableData = new ArrayList<>() ;
tableData.add("浙江"+i) ;
tableData.add("杭州"+i) ;
tableData.add("276"+i) ;
tableData.add("33.3%") ;
tableDataList.add(tableData) ;
}
return tableDataList ;
}
private static List tableHead (){
List tableHeadList = new ArrayList<>() ;
tableHeadList.add("省份") ;
tableHeadList.add("城市") ;
tableHeadList.add("數(shù)量") ;
tableHeadList.add("百分比") ;
return tableHeadList ;
}
public static void main(String[] args) throws Exception {
createPdfPage () ;
}
}
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-freemarker
Title
項目信息:
名稱:${name}
作者:${author}
public class PageConfig {
private static final String DEST = "F:\\file-type\\HTML頁面2020-01-15.pdf";
private static final String HTML = "/pdf_page_one.html";
private static final String FONT = "C:/Windows/Fonts/simsun.ttc";
private static Configuration freemarkerCfg = null ;
static {
freemarkerCfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
//freemarker的模板目錄
try {
String path = "TODO:模板路徑{自定義}" ;
freemarkerCfg.setDirectoryForTemplateLoading(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 創(chuàng)建文檔
*/
private static void createPdf(String content,String dest) throws Exception {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontImp.register(FONT);
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new ByteArrayInputStream(content.getBytes()), null, Charset.forName("UTF-8"), fontImp);
document.close();
}
/**
* 頁面渲染
*/
private static String freeMarkerRender(Map data, String htmlTmp) throws Exception {
Writer out = new StringWriter();
Template template = freemarkerCfg.getTemplate(htmlTmp,"UTF-8");
template.process(data, out);
out.flush();
out.close();
return out.toString();
}
/**
* 方法入口
*/
public static void main(String[] args) throws Exception {
Map data = new HashMap<> ();
data.put("name","smile");
data.put("author","知了") ;
String content = PageConfig.freeMarkerRender(data,HTML);
PageConfig.createPdf(content,DEST);
}
}
以上就是用SpringBoot管理PDF和Excel文件的方法,文中示例代碼較為詳細(xì)。如果想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!