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;
/**
* 封裝對(duì)excel的操作,包括本地讀寫(xiě)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 = "";
// 寫(xiě)入excel時(shí),是否自動(dòng)擴(kuò)展列寬度來(lái)符合內(nèi)容。
private boolean autoColumnWidth = false;
/**
* 無(wú)參構(gòu)造函數(shù) 默認(rèn)
*/
public ExcelUtil() {
}
/**
* 有參構(gòu)造函數(shù)
*
* @param path
* excel路徑
*/
public ExcelUtil(String path) {
this.path = path;
}
/**
* 讀取某個(gè)工作簿上的所有單元格的值。
*
* @param sheetOrder
* 工作簿序號(hào),從0開(kāi)始。
* @return List<Object[]> 所有單元格的值。
* @throws IOException
* 加載excel文件IO異常。
* @throws FileNotFoundException
* excel文件沒(méi)有找到異常。
* @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);
// 用來(lái)記錄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對(duì)象的方法
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;
}
/**
* 讀取某個(gè)工作簿上的某個(gè)單元格的值。
*
* @param sheetOrder
* 工作簿序號(hào),從0開(kāi)始。
* @param colum
* 列數(shù) 從1開(kāi)始
* @param row
* 行數(shù) 從1開(kāi)始
* @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;
}
/**
* 在指定的工作簿、行、列書(shū)寫(xiě)值。
*
* @param sheetOrder
* 工作簿序號(hào),基于0.
* @param colum
* 列 基于1
* @param row
* 行 基于1
* @param content
* 將要被書(shū)寫(xiě)的內(nèi)容。
* @throws Exception
* 書(shū)寫(xiě)后保存異常。
* @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();
}
/**
* 得到一個(gè)工作區(qū)最后一條記錄的序號(hào),相當(dāng)于這個(gè)工作簿共多少行數(shù)據(jù)。
*
* @param sheetOrder
* 工作區(qū)序號(hào)
* @return int 序號(hào)。
* @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();
}
/**
* 在磁盤(pán)生成一個(gè)含有內(nèi)容的excel,路徑為path屬性
*
* @param sheetName
* 導(dǎo)出的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();
}
/**
* 在輸出流中導(dǎo)出excel。
*
* @param excelName
* 導(dǎo)出的excel名稱 包括擴(kuò)展名
* @param sheetName
* 導(dǎo)出的sheet名稱
* @param fieldName
* 列名數(shù)組
* @param data
* 數(shù)據(jù)組
* @param response
* response
* @throws IOException
* 轉(zhuǎn)換流時(shí)IO錯(cuò)誤
* @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ù)條件,生成工作薄對(duì)象到內(nèi)存。
*
* @param sheetName
* 工作表對(duì)象名稱
* @param fieldName
* 首列列名稱
* @param data
* 數(shù)據(jù)
* @return HSSFWorkbook
* @author 宋立君
* @date 2014年07月03日
*/
private HSSFWorkbook makeWorkBook(String sheetName, String[] fieldName,
List<Object[]> data) {
// 用來(lái)記錄最大列寬,自動(dòng)調(diào)整列寬。
Integer collength[] = new Integer[fieldName.length];
// 產(chǎn)生工作薄對(duì)象
HSSFWorkbook workbook = new HSSFWorkbook();
// 產(chǎn)生工作表對(duì)象
HSSFSheet sheet = workbook.createSheet();
// 為了工作表能支持中文,設(shè)置字符集為UTF_16
workbook.setSheetName(0, sheetName);
// 產(chǎn)生一行
HSSFRow row = sheet.createRow(0);
// 產(chǎn)生單元格
HSSFCell cell;
// 寫(xiě)入各個(gè)字段的名稱
for (int i = 0; i < fieldName.length; i++) {
// 創(chuàng)建第一行各個(gè)字段名稱的單元格
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;
}
// 臨時(shí)單元格內(nèi)容
String tempCellContent = "";
// 寫(xiě)入各條記錄,每條記錄對(duì)應(yīng)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));
// 如果自動(dòng)調(diào)整列寬度。
if (autoColumnWidth) {
if (j >= collength.length) { // 標(biāo)題列數(shù)小于數(shù)據(jù)列數(shù)時(shí)。
collength = CollectionUtil.addObjectToArray(collength,
tempCellContent.getBytes().length);
} else {
// 如果這個(gè)內(nèi)容的寬度大于之前最大的,就按照這個(gè)設(shè)置寬度。
if (collength[j] < tempCellContent.getBytes().length) {
collength[j] = tempCellContent.getBytes().length;
}
}
}
}
}
// 自動(dòng)調(diào)整列寬度。
if (autoColumnWidth) {
// 調(diào)整列為這列文字對(duì)應(yīng)的最大寬度。
for (int i = 0; i < fieldName.length; i++) {
sheet.setColumnWidth(i, collength[i] * 2 * 256);
}
}
return workbook;
}
/**
* 功能:設(shè)置寫(xiě)入excel時(shí),是否自動(dòng)擴(kuò)展列寬度來(lái)符合內(nèi)容,默認(rèn)為false。
*
* @author 宋立君
* @date 2014年07月03日
* @param autoColumnWidth
* true或者false
*/
public void setAutoColumnWidth(boolean autoColumnWidth) {
this.autoColumnWidth = autoColumnWidth;
}
}
相關(guān)文章
深入解析JVM之內(nèi)存結(jié)構(gòu)及字符串常量池(推薦)
Java作為一種平臺(tái)無(wú)關(guān)性的語(yǔ)言,其主要依靠于Java虛擬機(jī)——JVM,接下來(lái)通過(guò)本文給大家介紹JVM之內(nèi)存結(jié)構(gòu)及字符串常量池的相關(guān)知識(shí),需要的朋友可以參考下2020-07-07
Spring事務(wù)中的事務(wù)傳播行為使用方式詳解
Spring框架作為一個(gè)輕量級(jí)的開(kāi)源框架,在企業(yè)應(yīng)用開(kāi)發(fā)中被廣泛使用,在Spring事務(wù)管理中,事務(wù)傳播行為是非常重要的一部分,它定義了方法如何參與到已經(jīng)存在的事務(wù)中或者如何開(kāi)啟新的事務(wù),本文將詳細(xì)介紹Spring事務(wù)中的幾種事務(wù)傳播行為,詳細(xì)講解具體使用方法2023-06-06
Maven創(chuàng)建項(xiàng)目過(guò)慢的4種解決辦法
最近經(jīng)常會(huì)遇到一個(gè)困擾,那就是用idea創(chuàng)建maven項(xiàng)目時(shí),速度很慢,本文就來(lái)介紹一下Maven創(chuàng)建項(xiàng)目過(guò)慢的4種解決辦法,感興趣的可以了解一下2021-12-12
SpringBoot實(shí)現(xiàn)定時(shí)任務(wù)和異步調(diào)用
這篇文章主要為大家詳細(xì)介紹了SpringBoot實(shí)現(xiàn)定時(shí)任務(wù)和異步調(diào)用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04
Spring Cloud Hystrix入門(mén)和Hystrix命令原理分析
這篇文章主要介紹了Spring Cloud Hystrix入門(mén)和Hystrix命令原理分析,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08
IDEA中sout快捷鍵無(wú)效問(wèn)題的解決方法
這篇文章主要介紹了IDEA中sout快捷鍵無(wú)效問(wèn)題,在類文件中進(jìn)行操作會(huì)造成sout快捷命令無(wú)法自動(dòng)生成,比如操作了import引入其它包之后,本文給大家分享解決方法,感興趣的朋友一起看看吧2022-07-07
使用EasyPoi完成復(fù)雜一對(duì)多excel表格導(dǎo)出功能全過(guò)程
這篇文章主要介紹了使用EasyPoi完成復(fù)雜一對(duì)多excel表格導(dǎo)出功能全過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12

