java常用工具類之Excel操作類及依賴包下載
更新時間:2014年07月05日 12:43:38 投稿:junjie
這篇文章主要介紹了java常用工具類Excel操作類及依賴包下載,需要的朋友可以參考下
依賴包下載:http://xiazai.jb51.net/201407/tools/java-excel-dependency(jb51.net).rar
Excel工具類ExcelUtil.java源碼:
package com.itjh.javaUtil; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.DecimalFormat; import java.util.LinkedList; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRichTextString; 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.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; 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.ss.usermodel.WorkbookFactory; /** * 封裝對excel的操作,包括本地讀寫excel和流中輸出excel,支持office 2007。<br/> * 依賴于poi-3.9-20121203.jar,poi-ooxml-3.9-20121203.jar,poi-ooxml-schemas-3.9- * 20121203.jar,dom4j-1.6.1.jar<br/> * 有參構(gòu)造函數(shù)參數(shù)為excel的全路徑<br/> * * @author 宋立君 * @date 2014年07月03日 */ public class ExcelUtil { // excel文件路徑 private String path = ""; // 寫入excel時,是否自動擴展列寬度來符合內(nèi)容。 private boolean autoColumnWidth = false; /** * 無參構(gòu)造函數(shù) 默認 */ public ExcelUtil() { } /** * 有參構(gòu)造函數(shù) * * @param path * excel路徑 */ public ExcelUtil(String path) { this.path = path; } /** * 讀取某個工作簿上的所有單元格的值。 * * @param sheetOrder * 工作簿序號,從0開始。 * @return List<Object[]> 所有單元格的值。 * @throws IOException * 加載excel文件IO異常。 * @throws FileNotFoundException * excel文件沒有找到異常。 * @throws InvalidFormatException * @author 宋立君 * @date 2014年07月03日 */ public List<Object[]> read(int sheetOrder) throws FileNotFoundException, IOException, InvalidFormatException { FileInputStream fis = new FileInputStream(path); Workbook workbook = WorkbookFactory.create(fis); if (fis != null) { fis.close(); } Sheet sheet = workbook.getSheetAt(sheetOrder); // 用來記錄excel值 List<Object[]> valueList = new LinkedList<Object[]>(); // 循環(huán)遍歷每一行、每一列。 for (Row row : sheet) { // 每一行 Object[] rowObject = null; for (Cell cell : row) { // cell.getCellType是獲得cell里面保存的值的type switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: // 得到Boolean對象的方法 rowObject = CollectionUtil.addObjectToArray(rowObject, cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: // 先看是否是日期格式 if (DateUtil.isCellDateFormatted(cell)) { // 讀取日期格式 rowObject = CollectionUtil.addObjectToArray(rowObject, cell.getDateCellValue()); } else { DecimalFormat df = new DecimalFormat(); // 單元格的值,替換掉, String value = df.format(cell.getNumericCellValue()) .replace(",", ""); // 讀取數(shù)字 rowObject = CollectionUtil.addObjectToArray(rowObject, value); } break; case Cell.CELL_TYPE_FORMULA: // 讀取公式 rowObject = CollectionUtil.addObjectToArray(rowObject, cell.getCellFormula()); break; case Cell.CELL_TYPE_STRING: // 讀取String rowObject = CollectionUtil.addObjectToArray(rowObject, cell .getRichStringCellValue().toString()); break; } } // 將這行添加到list。 valueList.add(rowObject); } return valueList; } /** * 讀取某個工作簿上的某個單元格的值。 * * @param sheetOrder * 工作簿序號,從0開始。 * @param colum * 列數(shù) 從1開始 * @param row * 行數(shù) 從1開始 * @return 單元格的值。 * @throws Exception * 加載excel異常。 * @author 宋立君 * @date 2014年07月03日 */ public String read(int sheetOrder, int colum, int row) throws Exception { FileInputStream fis = new FileInputStream(path); Workbook workbook = WorkbookFactory.create(fis); if (fis != null) { fis.close(); } Sheet sheet = workbook.getSheetAt(sheetOrder); Row rows = sheet.getRow(row - 1); Cell cell = rows.getCell(colum - 1); String content = cell.getStringCellValue(); return content; } /** * 在指定的工作簿、行、列書寫值。 * * @param sheetOrder * 工作簿序號,基于0. * @param colum * 列 基于1 * @param row * 行 基于1 * @param content * 將要被書寫的內(nèi)容。 * @throws Exception * 書寫后保存異常。 * @author 宋立君 * @date 2014年07月03日 */ public void write(int sheetOrder, int colum, int row, String content) throws Exception { FileInputStream fis = new FileInputStream(path); Workbook workbook = WorkbookFactory.create(fis); if (fis != null) { fis.close(); } Sheet sheet = workbook.getSheetAt(sheetOrder); Row rows = sheet.createRow(row - 1); Cell cell = rows.createCell(colum - 1); cell.setCellValue(content); FileOutputStream fileOut = new FileOutputStream(path); workbook.write(fileOut); fileOut.close(); } /** * 得到一個工作區(qū)最后一條記錄的序號,相當于這個工作簿共多少行數(shù)據(jù)。 * * @param sheetOrder * 工作區(qū)序號 * @return int 序號。 * @throws IOException * 根據(jù)excel路徑加載excel異常。 * @throws InvalidFormatException * @author 宋立君 * @date 2014年07月03日 */ public int getSheetLastRowNum(int sheetOrder) throws IOException, InvalidFormatException { FileInputStream fis = new FileInputStream(path); Workbook workbook = WorkbookFactory.create(fis); if (fis != null) { fis.close(); } Sheet sheet = workbook.getSheetAt(sheetOrder); return sheet.getLastRowNum(); } /** * 在磁盤生成一個含有內(nèi)容的excel,路徑為path屬性 * * @param sheetName * 導出的sheet名稱 * @param fieldName * 列名數(shù)組 * @param data * 數(shù)據(jù)組 * @throws IOException * @author 宋立君 * @date 2014年07月03日 */ public void makeExcel(String sheetName, String[] fieldName, List<Object[]> data) throws IOException { // 在內(nèi)存中生成工作薄 HSSFWorkbook workbook = makeWorkBook(sheetName, fieldName, data); // 截取文件夾路徑 String filePath = path.substring(0, path.lastIndexOf("\\")); // 如果路徑不存在,創(chuàng)建路徑 File file = new File(filePath); // System.out.println(path+"-----------"+file.exists()); if (!file.exists()) file.mkdirs(); FileOutputStream fileOut = new FileOutputStream(path); workbook.write(fileOut); fileOut.close(); } /** * 在輸出流中導出excel。 * * @param excelName * 導出的excel名稱 包括擴展名 * @param sheetName * 導出的sheet名稱 * @param fieldName * 列名數(shù)組 * @param data * 數(shù)據(jù)組 * @param response * response * @throws IOException * 轉(zhuǎn)換流時IO錯誤 * @author 宋立君 * @date 2014年07月03日 */ public void makeStreamExcel(String excelName, String sheetName, String[] fieldName, List<Object[]> data, HttpServletResponse response) throws IOException { OutputStream os = null; response.reset(); // 清空輸出流 os = response.getOutputStream(); // 取得輸出流 response.setHeader("Content-disposition", "attachment; filename=" + new String(excelName.getBytes(), "ISO-8859-1")); // 設(shè)定輸出文件頭 response.setContentType("application/msexcel"); // 定義輸出類型 // 在內(nèi)存中生成工作薄 HSSFWorkbook workbook = makeWorkBook(sheetName, fieldName, data); os.flush(); workbook.write(os); } /** * 根據(jù)條件,生成工作薄對象到內(nèi)存。 * * @param sheetName * 工作表對象名稱 * @param fieldName * 首列列名稱 * @param data * 數(shù)據(jù) * @return HSSFWorkbook * @author 宋立君 * @date 2014年07月03日 */ private HSSFWorkbook makeWorkBook(String sheetName, String[] fieldName, List<Object[]> data) { // 用來記錄最大列寬,自動調(diào)整列寬。 Integer collength[] = new Integer[fieldName.length]; // 產(chǎn)生工作薄對象 HSSFWorkbook workbook = new HSSFWorkbook(); // 產(chǎn)生工作表對象 HSSFSheet sheet = workbook.createSheet(); // 為了工作表能支持中文,設(shè)置字符集為UTF_16 workbook.setSheetName(0, sheetName); // 產(chǎn)生一行 HSSFRow row = sheet.createRow(0); // 產(chǎn)生單元格 HSSFCell cell; // 寫入各個字段的名稱 for (int i = 0; i < fieldName.length; i++) { // 創(chuàng)建第一行各個字段名稱的單元格 cell = row.createCell((short) i); // 設(shè)置單元格內(nèi)容為字符串型 cell.setCellType(HSSFCell.CELL_TYPE_STRING); // 為了能在單元格中輸入中文,設(shè)置字符集為UTF_16 // cell.setEncoding(HSSFCell.ENCODING_UTF_16); // 給單元格內(nèi)容賦值 cell.setCellValue(new HSSFRichTextString(fieldName[i])); // 初始化列寬 collength[i] = fieldName[i].getBytes().length; } // 臨時單元格內(nèi)容 String tempCellContent = ""; // 寫入各條記錄,每條記錄對應excel表中的一行 for (int i = 0; i < data.size(); i++) { Object[] tmp = data.get(i); // 生成一行 row = sheet.createRow(i + 1); for (int j = 0; j < tmp.length; j++) { cell = row.createCell((short) j); // 設(shè)置單元格字符類型為String cell.setCellType(HSSFCell.CELL_TYPE_STRING); tempCellContent = (tmp[j] == null) ? "" : tmp[j].toString(); cell.setCellValue(new HSSFRichTextString(tempCellContent)); // 如果自動調(diào)整列寬度。 if (autoColumnWidth) { if (j >= collength.length) { // 標題列數(shù)小于數(shù)據(jù)列數(shù)時。 collength = CollectionUtil.addObjectToArray(collength, tempCellContent.getBytes().length); } else { // 如果這個內(nèi)容的寬度大于之前最大的,就按照這個設(shè)置寬度。 if (collength[j] < tempCellContent.getBytes().length) { collength[j] = tempCellContent.getBytes().length; } } } } } // 自動調(diào)整列寬度。 if (autoColumnWidth) { // 調(diào)整列為這列文字對應的最大寬度。 for (int i = 0; i < fieldName.length; i++) { sheet.setColumnWidth(i, collength[i] * 2 * 256); } } return workbook; } /** * 功能:設(shè)置寫入excel時,是否自動擴展列寬度來符合內(nèi)容,默認為false。 * * @author 宋立君 * @date 2014年07月03日 * @param autoColumnWidth * true或者false */ public void setAutoColumnWidth(boolean autoColumnWidth) { this.autoColumnWidth = autoColumnWidth; } }
相關(guān)文章
JavaWeb開發(fā)之使用jQuery與Ajax實現(xiàn)動態(tài)聯(lián)級菜單效果
這篇文章主要介紹了JavaWeb開發(fā)之使用jQuery與Ajax實現(xiàn)動態(tài)聯(lián)級菜單效果的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-10-10Java中new關(guān)鍵字和newInstance方法的區(qū)別分享
在初始化一個類,生成一個實例的時候,newInstance()方法和new關(guān)鍵字除了一個是方法一個是關(guān)鍵字外,最主要的區(qū)別是創(chuàng)建對象的方式不同2013-07-07IntelliJ Idea 2020.1 正式發(fā)布,官方支持中文(必看)
這篇文章主要介紹了IntelliJ Idea 2020.1 正式發(fā)布,官方支持中文了,本文通過截圖的形式給大家展示,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04