用Java玩轉(zhuǎn)Excel,竟然如此easy~
點(diǎn)擊上方?好好學(xué)java?,選擇?星標(biāo)?公眾號(hào)
重磅資訊,干貨,第一時(shí)間送達(dá)
今日推薦:分享一套基于SpringBoot和Vue的企業(yè)級(jí)中后臺(tái)開(kāi)源項(xiàng)目,這個(gè)項(xiàng)目有點(diǎn)哇塞!
個(gè)人原創(chuàng)100W +訪問(wèn)量博客:點(diǎn)擊前往,查看更多
來(lái)源:https://www.cnblogs.com/deng-cc
1、POI是什么
<dependency><groupId>org.apache.poigroupId><artifactId>poiartifactId><version>3.9version>dependency><dependency><groupId>org.apache.poigroupId><artifactId>poi-ooxmlartifactId><version>3.9version>dependency>
HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format.XSSF?is?the?POI?Project's?pure?Java?implementation?of?the?Excel?2007?OOXML?(.xlsx)?file?format.
2、POI核心類
2.1 工作簿 Workbook
HSSFWorkbook : 有讀取.xls 格式和寫入Microsoft Excel文件的方法。它與微軟Office97-2003版本兼容
XSSFWorkbook : 有讀寫Microsoft Excel和OpenOffice的XML文件的格式.xls或.xlsx的方法。它與MS-Office版本2007或更高版本兼容
//直接創(chuàng)建新的HSSFWorkbook()//通過(guò)輸入流創(chuàng)建HSSFWorkbook(java.io.InputStream s)
//直接創(chuàng)建新的XSSFWorkbook()//通過(guò)File類創(chuàng)建XSSFWorkbook(java.io.File file)//通過(guò)輸入流創(chuàng)建XSSFWorkbook(java.io.InputStream is)
2.2 標(biāo)簽頁(yè) Sheet
workbook.createSheet();workbook.createSheet(String?sheetName);
2.3 行 Row
sheet.createRow(int rownum);
2.4 單元格 Cell
row.createCell(int?column);row.createCell(int?column,?int?type);
3、創(chuàng)建和讀取
import java.io.*;import org.apache.poi.xssf.usermodel.*;public class CreateWorkBook{public static void main(String[] args)throws Exception{Blank workbookXSSFWorkbook workbook = new XSSFWorkbook();file system using specific nameFileOutputStream out = new FileOutputStream(new File("createworkbook.xlsx"));operation workbook using file out objectworkbook.write(out);out.close();System.out.println("written successfully");}}
3.2 打開(kāi)現(xiàn)有的工作簿
import java.io.*;import org.apache.poi.xssf.usermodel.*;public class OpenWorkBookpublic static void main(String args[])throws ExceptionFile file = new File("openworkbook.xlsx");FileInputStream fIP = new FileInputStream(file);//Get the workbook instance for XLSX fileXSSFWorkbook workbook = new XSSFWorkbook(fIP);if(file.isFile() && file.exists()){System.out.println("openworkbook.xlsx file open successfully.");}else{System.out.println("Error to open openworkbook.xlsx file.");}}}
4、方法示例:任意對(duì)象List轉(zhuǎn)至為Excel文檔(可用注解定義標(biāo)簽名和列名)
(name = "學(xué)生標(biāo)簽頁(yè)")public class Student {(name = "姓名")private String name;private boolean male;(name = "身高")private int height;public String getName() {return name;}public void setName(String name) {this.name = name;}public boolean isMale() {return male;}public void setMale(boolean male) {this.male = male;}public int getHeight() {return height;}public void setHeight(int height) {this.height = height;}}
public static void main(String[] args) {Listlist = new ArrayList (); Student student1 = new Student();student1.setName("小紅");student1.setMale(false);student1.setHeight(167);Student student2 = new Student();student2.setName("小明");student2.setMale(true);student2.setHeight(185);list.add(student1);list.add(student2);File file = new File("C:/Users/Dulk/Desktop/1314.xls");createExcel(list, file);}

import?java.lang.annotation.Retention;import?java.lang.annotation.RetentionPolicy;public??Excel?{????//設(shè)置名稱????public?String?name()?default?"";}
import org.apache.log4j.Logger;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.List;/**Excel的操作工具類*/public class ExcelUtil {private static Logger log = Logger.getLogger(ExcelUtil.class);/**獲取某個(gè)File文件對(duì)應(yīng)的Workbook工作簿對(duì)象*/public static Workbook gainWorkbook(File file) throws ExcelException {if (!isExcel(file)) {throw new ExcelException("文件不是Excel類型");}//如果文件不存在則新建if (!file.exists()) {try {OutputStream os = new FileOutputStream(file);Workbook workbook = isOlderEdition(file) ? new HSSFWorkbook() : new XSSFWorkbook();workbook.write(os);log.debug("文件不存在,新建該Excel文件");os.close();catch (FileNotFoundException e) {e.printStackTrace();catch (IOException e) {e.printStackTrace();}}try {InputStream is = new FileInputStream(file);return isOlderEdition(file) ? new HSSFWorkbook(is) : new XSSFWorkbook(is);catch (FileNotFoundException e) {e.printStackTrace();catch (IOException e) {e.printStackTrace();}return null;}/**判斷某個(gè)Excel文件是否是2003-2007通用舊版*/private static boolean isOlderEdition(File file) {return file.getName().matches(".+\\.(?i)xls");}/**判斷文件是否是一個(gè)Excel文件*/private static boolean isExcel(File file) {String fileName = file.getName();String regXls = ".+\\.(?i)xls";String regXlsx = ".+\\.(?i)xlsx";return fileName.matches(regXls) || fileName.matches(regXlsx);}/**將某個(gè)對(duì)象的List轉(zhuǎn)換為Excel工作簿*/public staticWorkbook createExcel(List list, File file) { String sheetName = "default";if (list.size() == 0) {return null;}Workbook workbook = null;try {Class clazz = list.get(0).getClass();fields = clazz.getDeclaredFields();if (clazz.isAnnotationPresent(Excel.class)) {Excel excel = (Excel) clazz.getAnnotation(Excel.class);sheetName = excel.name();}workbook = gainWorkbook(file);Sheet sheet = workbook.createSheet(sheetName);//創(chuàng)建首行Row line = sheet.createRow(0);for (int k = 0; k < fields.length; k++) {Cell cell = line.createCell(k);String columnName = fields[k].getName();if (fields[k].isAnnotationPresent(Excel.class)) {Excel excel = fields[k].getAnnotation(Excel.class);columnName = excel.name();}cell.setCellValue(columnName);}//創(chuàng)建數(shù)據(jù)for (int i = 1; i <= list.size(); i++) {Row row = sheet.createRow(i);for (int j = 1; j <= fields.length; j++) {Cell cell = row.createCell(j - 1);String fieldName = fields[j - 1].getName();String fieldFirstLetterUpper = fieldName.substring(0, 1).toUpperCase();String prefix = "get";if ("boolean".equals(fields[j - 1].getType().getName())) {prefix = "is";}String methodName = prefix + fieldFirstLetterUpper + fieldName.substring(1);Method method = clazz.getMethod(methodName);- 1))));}}log.debug("List讀入完畢");OutputStream os = new FileOutputStream(file);workbook.write(os);os.close();catch (ExcelException e) {e.printStackTrace();catch (InvocationTargetException e) {e.printStackTrace();catch (NoSuchMethodException e) {e.printStackTrace();catch (IllegalAccessException e) {e.printStackTrace();catch (FileNotFoundException e) {e.printStackTrace();catch (IOException e) {e.printStackTrace();}return workbook;}}
推薦文章
分享一套基于SpringBoot和Vue的企業(yè)級(jí)中后臺(tái)開(kāi)源項(xiàng)目,這個(gè)項(xiàng)目有點(diǎn)哇塞!
圈子哥推薦一種基于Spring Boot開(kāi)發(fā)OA開(kāi)源產(chǎn)品,學(xué)習(xí)/搞外快都是不二選擇!
原創(chuàng)電子書
歷時(shí)整整一年總結(jié)的?Java面試+ Java入門技術(shù)學(xué)習(xí)指南,這是本人這幾年及校招的總結(jié),各種異步面試題已經(jīng)全部進(jìn)行總結(jié),按照章節(jié)復(fù)習(xí)即可,已經(jīng)拿到了了大廠提供。
原創(chuàng)思維導(dǎo)圖
掃碼或者微信搜?程序員的技術(shù)圈子?回復(fù)?面試?領(lǐng)取原創(chuàng)電子書和思維導(dǎo)圖。
評(píng)論
圖片
表情



