如題所示,當咱們須要在Java中解析Excel文件時,能夠考慮使用JXL或POI的API來解析。html
兩者的區別以下:java
jxl如今基本上沒被維護了,最近一次更新時間仍是幾年前。相反,poi屬於Apache開源項目的一部分,更新維護得比較好,最新穩定版 POI 3.15 是今年(2016年)9月更新的,同時poi能夠支持更高版本的excel,而jxl只能支持excel2003以及以前的版本數據庫
小文件使用jxl解析效率比較高,可是由於支持的excel版本的限制,致使不能導出65535以上量級的數據apache
總之,我建議使用POI來生成解析excel文件。關於生成和解析excel文件的流程實際上跟Java生成和解析xml文件(PS:關於這部分的內容能夠參考個人這篇文章:https://www.zifangsky.cn/596.html)是差很少的,所以我下面就直接貼示例代碼了。固然,代碼裏面有詳細的註釋供你們參考api
jxl-2.6.12.jar下載地址:http://maven.outofmemory.cn/net.sourceforge.jexcelapi/jxl/2.6/dom
package cn.zifangsky.excel; import java.io.File; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class JXLDemo { /** * JXL建立Excel文件 * * @param fileUrl * 文件路徑 * @return null */ public static void createExcel(String fileUrl) { String[] title = { "title1", "title2", "title3" }; // 建立Excel文件 File firstExcelFile = new File(fileUrl); try { // 建立工做簿 WritableWorkbook workbook = Workbook.createWorkbook(firstExcelFile); // 建立sheet WritableSheet sheet = workbook.createSheet("demo", 0); Label label = null; // 單元格 // 設置第一行的標題 for (int i = 0; i < title.length; i++) { label = new Label(i, 0, title[i]); sheet.addCell(label); } // 添加幾行數據 for (int i = 0; i < title.length; i++) { for (int j = 1; j < 11; j++) { label = new Label(i, j, String.valueOf(i + j)); sheet.addCell(label); } } workbook.write(); workbook.close(); } catch (Exception e) { e.printStackTrace(); } } /** * JXL解析Excel文件 * * @param fileUrl * 文件路徑 * @return null */ public static void resolveExcel(String fileUrl) { try { Workbook workbook = Workbook.getWorkbook(new File(fileUrl)); // 獲取工做表中的第一個sheet Sheet sheet = workbook.getSheet(0); for (int i = 0; i < sheet.getRows(); i++) { for (int j = 0; j < sheet.getColumns(); j++) { Cell cell = sheet.getCell(j, i); System.out.print(cell.getContents() + " "); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { JXLDemo.createExcel("C:/Users/Administrator/Desktop/jxlExcel.xls"); JXLDemo.resolveExcel("C:/Users/Administrator/Desktop/jxlExcel.xls"); } }
生成的excel文件以下所示:xss
最後輸出以下:maven
title1 title2 title3 1 2 3 2 3 4 3 4 5 4 5 6 5 6 7 6 7 8 7 8 9 8 9 10 9 10 11 10 11 12
jar包下載地址:http://poi.apache.org/download.htmlide
(1)生成和解析低版本的Excel文件:測試
package cn.zifangsky.excel; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class POIDemo { /** * POI建立Excel文件 * * @param fileUrl * 文件路徑 * @return null */ public static void createExcel(String fileUrl) { String[] title = { "title1", "title2", "title3" }; // 建立工做簿 HSSFWorkbook workbook = new HSSFWorkbook(); // 建立sheet HSSFSheet sheet = workbook.createSheet("demo"); // 設置第一行的標題 HSSFRow firstRow = sheet.createRow(0); HSSFCell cell = null; for (int i = 0; i < title.length; i++) { cell = firstRow.createCell(i); cell.setCellValue(title[i]); } // 添加幾行數據 for (int i = 0; i < 10; i++) { HSSFRow nextRow = sheet.createRow(i + 1); for (int j = 0; j < title.length; j++) { cell = nextRow.createCell(j); cell.setCellValue(i * j); } } // 建立Excel文件 File POIExcelFile = new File(fileUrl); try { POIExcelFile.createNewFile(); OutputStream outputStream = new FileOutputStream(POIExcelFile); workbook.write(outputStream); outputStream.close(); workbook.close(); } catch (IOException e) { e.printStackTrace(); } } /** * POI解析Excel文件 * * @param fileUrl * 文件路徑 * @return null */ public static void resolveExcel(String fileUrl) { File POIExcelFile = new File(fileUrl); try { InputStream inputStream = new FileInputStream(POIExcelFile); // 建立工做簿 HSSFWorkbook workbook = new HSSFWorkbook(inputStream); // 建立sheet // HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheet("demo"); int firstRowNum = sheet.getFirstRowNum(); // 第一行的行號 int lastRowNum = sheet.getLastRowNum(); // 最後一行的行號 // 循環遍歷每個單元格 for (int row = firstRowNum; row <= lastRowNum; row++) { HSSFRow eachRow = sheet.getRow(row); // 每一行 int firstCellNum = eachRow.getFirstCellNum(); // 第一列的列號 int lastCellNum = eachRow.getLastCellNum(); // 最後一列的列號 for (int column = firstCellNum; column < lastCellNum; column++) { HSSFCell cell = eachRow.getCell(column); if (row == 0) System.out.print(cell.getStringCellValue() + " "); else System.out.print(cell.getNumericCellValue() + " "); } System.out.println(); } workbook.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { POIDemo.createExcel("C:/Users/Administrator/Desktop/poiExcel.xls"); POIDemo.resolveExcel("C:/Users/Administrator/Desktop/poiExcel.xls"); } }
生成的excel文件以下:
控制檯輸出以下:
title1 title2 title3 0.0 0.0 0.0 0.0 1.0 2.0 0.0 2.0 4.0 0.0 3.0 6.0 0.0 4.0 8.0 0.0 5.0 10.0 0.0 6.0 12.0 0.0 7.0 14.0 0.0 8.0 16.0 0.0 9.0 18.0
(2)生成和解析高版本的Excel文件:
其實使用POI生成高版本的excel文件,只須要將HSSFWorkbook、HSSFSheet、HSSFRow、HSSFCell等類分別替換成:XSSFWorkbook、XSSFSheet、XSSFRow、XSSFCell等類便可,也就是將每一個類最前面的「H」換成「X」便可
示例代碼以下:
package cn.zifangsky.excel; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class POIDemo2 { /** * POI建立高版本Excel文件 * * @param fileUrl * 文件路徑 * @return null */ public static void createExcel(String fileUrl) { String[] title = { "title1", "title2", "title3" }; // 建立工做簿 XSSFWorkbook workbook = new XSSFWorkbook(); // 建立sheet XSSFSheet sheet = workbook.createSheet("demo"); // 設置第一行的標題 XSSFRow firstRow = sheet.createRow(0); XSSFCell cell = null; for (int i = 0; i < title.length; i++) { cell = firstRow.createCell(i); cell.setCellValue(title[i]); } // 添加幾行數據 for (int i = 0; i < 10; i++) { XSSFRow nextRow = sheet.createRow(i + 1); for (int j = 0; j < title.length; j++) { cell = nextRow.createCell(j); cell.setCellValue(i * j); } } // 建立Excel文件 File POIExcelFile = new File(fileUrl); try { POIExcelFile.createNewFile(); OutputStream outputStream = new FileOutputStream(POIExcelFile); workbook.write(outputStream); outputStream.close(); workbook.close(); } catch (IOException e) { e.printStackTrace(); } } /** * POI解析高版本Excel文件 * * @param fileUrl * 文件路徑 * @return null */ public static void resolveExcel(String fileUrl) { File POIExcelFile = new File(fileUrl); try { InputStream inputStream = new FileInputStream(POIExcelFile); // 建立工做簿 XSSFWorkbook workbook = new XSSFWorkbook(inputStream); // 建立sheet // HSSFSheet sheet = workbook.getSheetAt(0); XSSFSheet sheet = workbook.getSheet("demo"); int firstRowNum = sheet.getFirstRowNum(); // 第一行的行號 int lastRowNum = sheet.getLastRowNum(); // 最後一行的行號 // 循環遍歷每個單元格 for (int row = firstRowNum; row <= lastRowNum; row++) { XSSFRow eachRow = sheet.getRow(row); // 每一行 int firstCellNum = eachRow.getFirstCellNum(); // 第一列的列號 int lastCellNum = eachRow.getLastCellNum(); // 最後一列的列號 for (int column = firstCellNum; column < lastCellNum; column++) { XSSFCell cell = eachRow.getCell(column); if (row == 0) System.out.print(cell.getStringCellValue() + " "); else System.out.print(cell.getNumericCellValue() + " "); } System.out.println(); } workbook.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { POIDemo2.createExcel("C:/Users/Administrator/Desktop/poiExcel2.xlsx"); POIDemo2.resolveExcel("C:/Users/Administrator/Desktop/poiExcel2.xlsx"); } }
生成的excel文件以下:
最後輸出以下:
title1 title2 title3 0.0 0.0 0.0 0.0 1.0 2.0 0.0 2.0 4.0 0.0 3.0 6.0 0.0 4.0 8.0 0.0 5.0 10.0 0.0 6.0 12.0 0.0 7.0 14.0 0.0 8.0 16.0 0.0 9.0 18.0
(3)結合Java解析xml建立excel導出模板:
若是咱們須要按期將數據庫中的部分數據導出到excel中,那麼咱們能夠預先建立一個excel導出時的模板,之後每次導出數據時就能夠根據這個模板導出格式統一的報表了。關於這個模板的格式咱們能夠定義在一個xml文件中,而後用Java解析這個xml文件讀取樣式便可
i)模板格式的xml文件student.xml:
<?xml version="1.0" encoding="UTF-8"?> <excel id="student" code="student" name="學生信息導入"> <colgroup> <col index="A" width='17em'></col> <col index="B" width='17em'></col> <col index="C" width='17em'></col> <col index="D" width='17em'></col> <col index="E" width='17em'></col> <col index="F" width='17em'></col> </colgroup> <title> <tr height="16px" rowspan="2"> <td colspan="6" value="學生信息導入" /> </tr> <tr height="14px" rowspan="1"> <td colspan="3" value="基礎信息" /> <td colspan="3" value="擴展信息" /> </tr> </title> <thead> <tr height="12px"> <th value="編號" /> <th value="姓名" /> <th value="性別" /> <th value="年齡" /> <th value="出生日期" /> <th value=" 愛好" /> </tr> </thead> </excel>
(2)模板建立示例:
package cn.zifangsky.excel; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class CreateTemplate { public static void main(String[] args) { SAXReader reader = new SAXReader(); try { Document document = reader.read(new File("src/cn/zifangsky/excel/student.xml")); Element rootElement = document.getRootElement(); // 建立工做簿 XSSFWorkbook workbook = new XSSFWorkbook(); // 建立sheet XSSFSheet sheet = workbook.createSheet("Sheet0"); // 獲取模板名稱 String templateName = rootElement.attributeValue("name"); int rowNum = 0; // 初始行號 // 設置列寬 Element colGroup = rootElement.element("colgroup"); setColumnWidth(sheet, colGroup); // 設置標題 Element title = rootElement.element("title"); rowNum = setTitle(workbook, sheet, title, rowNum); // 設置表頭 Element thead = rootElement.element("thead"); rowNum = setHead(workbook, sheet, thead, rowNum); // 建立Excel文件 File POIExcelFile = new File("C:/Users/Administrator/Desktop/template.xlsx"); POIExcelFile.createNewFile(); OutputStream outputStream = new FileOutputStream(POIExcelFile); workbook.write(outputStream); outputStream.close(); workbook.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 單位轉換 */ public static int convert(String value) { // 獲得寬度單位 String unit = value.replaceAll("\\d", ""); // 去除非數字字符 String num = value.replaceAll("\\D", ""); int v = 0; if (StringUtils.isNotBlank(unit) && StringUtils.isNotBlank(num)) if (unit.equals("em")) { v = Math.round(Float.valueOf(num) * 267.5F); } else if (unit.equals("px")) { v = Math.round(Float.valueOf(num) * 20F); } return v; } /** * 設置列寬 */ private static void setColumnWidth(XSSFSheet sheet, Element colGroup) { List<Element> cols = colGroup.elements(); for (int i = 0; i < cols.size(); i++) { Element col = cols.get(i); Attribute widthAttribute = col.attribute("width"); // 設置寬度 sheet.setColumnWidth(i, convert(widthAttribute.getValue())); } } /** * 設置標題相關內容 */ private static int setTitle(XSSFWorkbook workbook, XSSFSheet sheet, Element title, int rowNum) { List<Element> trs = title.elements("tr"); int rspan = 0; // 橫跨多少行 int cspan = 0; // 橫跨多少列 // 遍歷多行標題 for (int i = 0; i < trs.size(); i++, rowNum += rspan) { Element tr = trs.get(i); Attribute rowSpan = tr.attribute("rowspan"); Attribute height = tr.attribute("height"); rspan = Integer.valueOf(rowSpan.getValue()); List<Element> tds = tr.elements("td"); XSSFRow row = sheet.createRow(rowNum); // 遍歷標題中的多列子標題 for (int j = 0, colNum = 0; j < tds.size(); j++, colNum += cspan) { // 表格樣式 XSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(HorizontalAlignment.CENTER); // 居中 Element td = tds.get(j); XSSFCell cell = row.createCell(colNum); Attribute colSpan = td.attribute("colspan"); Attribute value = td.attribute("value"); cspan = Integer.valueOf(colSpan.getValue()); if (value != null) { cell.setCellValue(value.getValue()); // 設置字體 XSSFFont font = workbook.createFont(); font.setFontName("宋體"); font.setBold(true); font.setFontHeight((short) convert(height.getValue())); cellStyle.setFont(font); cell.setCellStyle(cellStyle); // 合併單元格 sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum + rspan - 1, colNum, colNum + cspan - 1)); } } } return rowNum; } /** * 設置表頭相關內容 */ private static int setHead(XSSFWorkbook workbook, XSSFSheet sheet, Element thead, int rowNum) { List<Element> trs = thead.elements("tr"); for (int i = 0; i < trs.size(); i++, rowNum++) { Element tr = trs.get(i); XSSFRow row = sheet.createRow(rowNum); Attribute height = tr.attribute("height"); List<Element> ths = tr.elements("th"); for (int j = 0; j < ths.size(); j++) { // 表格樣式 XSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(HorizontalAlignment.CENTER); // 居中 Element th = ths.get(j); Attribute value = th.attribute("value"); XSSFCell cell = row.createCell(j); if (value != null) { cell.setCellValue(value.getValue()); // 設置字體 XSSFFont font = workbook.createFont(); font.setFontName("宋體"); font.setFontHeight((short) convert(height.getValue())); cellStyle.setFont(font); cell.setCellStyle(cellStyle); } } } return rowNum; } }
最後生成的模板文件以下:
注:我這裏僅僅只是寫了一個生成模板文件的測試代碼,所以涉及到JDBC方面的操做就省略掉了
PS:上面圖片中的水印是我我的博客的域名,所以還請管理員手下留情不要給我標爲「轉載文章」,謝謝!!!