如何利用java的反射機(jī)制讀取excel表格數(shù)據(jù)?這篇文章運(yùn)用了實(shí)例代碼展示,代碼非常詳細(xì),可供感興趣的小伙伴們參考借鑒,希望對(duì)大家有所幫助。

邢臺(tái)網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)公司!從網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、APP開(kāi)發(fā)、響應(yīng)式網(wǎng)站開(kāi)發(fā)等網(wǎng)站項(xiàng)目制作,到程序開(kāi)發(fā),運(yùn)營(yíng)維護(hù)。創(chuàng)新互聯(lián)公司從2013年開(kāi)始到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來(lái)保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)公司。
如下excel表格,按照表頭名字讀取數(shù)據(jù),允許表頭增加無(wú)意義空格,允許表頭順序交換。
| 序號(hào) | 隧道左公里標(biāo) | 隧道右公里標(biāo) | 是否隧道 |
| 1 | DK2291.416 | DK0 | 是 |
| 2 | DK7389.65 | DK2291.416 | 否 |
| 3 | ZK2277 | ZK0 | 是 |
| 4 | ZK5235.68 | ZK2277 | 否 |
excel導(dǎo)入工具類,提取配置表格文件順序,模糊動(dòng)態(tài)匹配表頭名字和順序。
/**
*
*/
package com.crscd.config.service.cbtc2.atp.excel;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
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.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import jcifs.smb.SmbFileInputStream;
/**
* @author ZhaoAnan
* @param <T>
*
*/
public class ExcelUtils<T> {
private Workbook workbook;
private OutputStream os;
private String pattern;// 日期格式
private final static String excel2003L = ".xls"; // 2003- 版本的excel
private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel
public void setPattern(String pattern) {
this.pattern = pattern;
}
public void ExcelUtil(Workbook workboook) {
this.workbook = workboook;
}
/**
* 描述:根據(jù)文件后綴,自適應(yīng)上傳文件的版本
*
* @param inStr 將file.getInputStream()獲取的輸入流
* @param fileName file.getOriginalFilename()獲取的原文件名
*/
public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if (excel2003L.equals(fileType)) {
wb = new HSSFWorkbook(inStr); // 2003-
} else if (excel2007U.equals(fileType)) {
wb = new XSSFWorkbook(inStr); // 2007+
} else {
throw new Exception("解析的文件格式有誤!");
}
return wb;
}
@Override
public String toString() {
return "共有 " + getSheetCount() + "個(gè)sheet 頁(yè)!";
}
public String toString(int sheetIx) throws IOException {
return "第 " + (sheetIx + 1) + "個(gè)sheet 頁(yè),名稱: " + getSheetName(sheetIx) + ",共 " + getRowCount(sheetIx) + "行!";
}
/**
*
* 根據(jù)后綴判斷是否為 Excel 文件,后綴匹配xls和xlsx
*
* @param pathname
* @return
*
*/
public static boolean isExcel(String pathname) {
if (pathname == null) {
return false;
}
return pathname.endsWith(".xls") || pathname.endsWith(".xlsx");
}
/**
*
* 讀取 Excel 第一頁(yè)所有數(shù)據(jù)
*
* @return
* @throws Exception
*
*/
public List<List<String>> read() throws Exception {
return read(0, 0, getRowCount(0) - 1);
}
/**
*
* 讀取指定sheet 頁(yè)所有數(shù)據(jù)
*
* @param sheetIx 指定 sheet 頁(yè),從 0 開(kāi)始
* @return
* @throws Exception
*/
public List<List<String>> read(int sheetIx) throws Exception {
return read(sheetIx, 0, getRowCount(sheetIx) - 1);
}
/**
*
* 讀取指定sheet 頁(yè)所有<T>數(shù)據(jù)
*
* @param sheetIx 指定 sheet 頁(yè),從 0 開(kāi)始
* @return
* @throws Exception
*/
public List<List<T>> readGeneric(int sheetIx, T t) throws Exception {
return readGeneric(sheetIx, 0, getRowCount(sheetIx) - 1, t);
}
/**
*
* 讀取指定sheet 頁(yè)指定行數(shù)據(jù)
*
* @param sheetIx 指定 sheet 頁(yè),從 0 開(kāi)始
* @param start 指定開(kāi)始行,從 0 開(kāi)始
* @param end 指定結(jié)束行,從 0 開(kāi)始
* @return
* @throws Exception
*/
public List<List<String>> read(int sheetIx, int start, int end) throws Exception {
Sheet sheet = workbook.getSheetAt(sheetIx);
List<List<String>> list = new ArrayList<List<String>>();
if (end > getRowCount(sheetIx)) {
end = getRowCount(sheetIx);
}
int cols = sheet.getRow(0).getLastCellNum(); // 第一行總列數(shù)
for (int i = start; i <= end; i++) {
List<String> rowList = new ArrayList<String>();
Row row = sheet.getRow(i);
for (int j = 0; j < cols; j++) {
if (row == null) {
rowList.add(null);
continue;
}
try {
if (row.getCell(j).getCellTypeEnum() == CellType.FORMULA) {
row.getCell(j).setCellType(CellType.STRING);
rowList.add(row.getCell(j).getStringCellValue());
}else {
rowList.add(getCellValueToString(row.getCell(j)));
}
}catch(Exception e) {
rowList.add(getCellValueToString(row.getCell(j)));
}
}
list.add(rowList);
}
return list;
}
/**
* 獲取某sheet某行的數(shù)據(jù)
*
* @param sheetIx
* @param rowNum
* @param colNum
* @return
* @throws Exception
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public List getRowdata(Row row) throws Exception {
List list = new ArrayList();
int cols = row.getLastCellNum();
for (int j = 0; j < cols; j++) {
//list.add(getCellValueToString(row.getCell(j)));
//取excel表中公式數(shù)據(jù) add by gaofan 20190618
try {
if (row.getCell(j).getCellTypeEnum() == CellType.FORMULA) {
row.getCell(j).setCellType(CellType.STRING);
list.add(getCellValueToString(row.getCell(j)));
}else {
list.add(getCellValueToString(row.getCell(j)));
}
}catch(Exception e) {
list.add(getCellValueToString(row.getCell(j)));
}
}
return list;
}
/**
*
* 讀取指定sheet 頁(yè)指定行<T>數(shù)據(jù)
*
* @param sheetIx 指定 sheet 頁(yè),從 0 開(kāi)始
* @param start 指定開(kāi)始行,從 0 開(kāi)始
* @param end 指定結(jié)束行,從 0 開(kāi)始
* @return
* @throws Exception
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<List<T>> readGeneric(int sheetIx, int start, int end, T t) throws Exception {
Sheet sheet = workbook.getSheetAt(sheetIx);
List<List<T>> list = new ArrayList<List<T>>();
if (end > getRowCount(sheetIx)) {
end = getRowCount(sheetIx);
}
List<Integer> colNums = new ArrayList<Integer>();
for (int i = start; i <= end; i++) {
List<T> rowList = new ArrayList<T>();
Row row = sheet.getRow(i);
List rowdata = getRowdata(row);
Class clazz = t.getClass();
Object fa= clazz.newInstance();
Method method = t.getClass().getMethod("getLdcode", new Class[]{});
String[] ldcode = (String[])method.invoke(fa, new Object[]{});
//處理從0行開(kāi)始取得請(qǐng)求
if(0 == start)
{
//處理請(qǐng)求的第0行,即表頭
if(i == 0)
{
//通過(guò)反射獲取模板類的實(shí)例
try {
String simpleName = t.getClass().getSimpleName();
String StrEnumClass = simpleName.substring(0, simpleName.length()-5) + "Enum";
Class EnumClass = Class.forName("com.crscd.config.service.cbtc2.atp.excel.enums."+StrEnumClass);
//Object enumInstance = EnumClass.newInstance();
for(int j = 0; j < rowdata.size(); j++)
{
//去除表頭上空格、回車、換行符、制表符
if(null != rowdata.get(j) && !"".equals(rowdata.get(j))) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
String str = (String)rowdata.get(j);
Matcher m = p.matcher(str);
String excelData = m.replaceAll("");
//獲取表頭對(duì)應(yīng)的工具類中l(wèi)dcode位置
Method met = EnumClass.getMethod("getStatus", String.class);
int col = (int) met.invoke(Object.class, excelData);
colNums.add(col);
}else
{
colNums.add(-1);
}
}
}catch(ClassNotFoundException e) {
//e.printStackTrace();
}
}
}
for(int j = 0; j < colNums.size(); j++) {
int k = j;
//如果映射表頭列和數(shù)據(jù)列不匹配,當(dāng)數(shù)據(jù)列小于映射表頭列時(shí),說(shuō)明excel有無(wú)效列,則不足的列用空串補(bǔ)足
if (colNums.size() > rowdata.size() ) {
rowdata.add("");
}
if(0 == start && !colNums.isEmpty())
{
k = colNums.get(j);
}
if(k == -1) {
continue;
}else {
try {
method = t.getClass().getMethod("set"+ldcode[k], String.class);
method.invoke(fa, rowdata.get(j));
//如果映射表頭列和數(shù)據(jù)列不匹配,是excel多余無(wú)效行列,則越界,仍保留未越界之前的全部數(shù)據(jù)。
}catch(IndexOutOfBoundsException e) {
continue;
}
}
}
rowList.add((T) fa);
list.add(rowList);
}
return list;
}
/**
*
* 讀取指定sheet 頁(yè)指定行數(shù)據(jù)
*
* @param sheetIx 指定 sheet 頁(yè),從 0 開(kāi)始
* @param startRow 指定開(kāi)始行,從 0 開(kāi)始
* @param endRow 指定結(jié)束行,從 0 開(kāi)始 start=end=0 就是第一行
* @param startCol 指定開(kāi)始列
* @param startCol 指定結(jié)束列
* @return
* @throws Exception
*/
public List<List<String>> read(int sheetIx, int startRow, int endRow, int startCol, int endCols) throws Exception {
Sheet sheet = workbook.getSheetAt(sheetIx);
List<List<String>> list = new ArrayList<List<String>>();
if (endRow > getRowCount(sheetIx)) {
endRow = getRowCount(sheetIx);
}
for (int i = startRow; i <= endRow; i++) {
List<String> rowList = new ArrayList<String>();
Row row = sheet.getRow(i);
for (int j = startCol; j <= endCols; j++) {
if (row == null) {
rowList.add(null);
continue;
}
//rowList.add(getCellValue(row.getCell(j)));
//取excel表中公式數(shù)據(jù) add by gaofan 20190618
try {
if (row.getCell(j).getCellTypeEnum() == CellType.FORMULA) {
row.getCell(j).setCellType(CellType.STRING);
rowList.add(row.getCell(j).getStringCellValue());
}else {
rowList.add(getCellValueToString(row.getCell(j)));
}
}catch(Exception e) {
rowList.add(getCellValueToString(row.getCell(j)));
}
}
list.add(rowList);
}
return list;
}
/**
* 獲取某sheet某行某列的數(shù)據(jù)
*
* @param sheetIx
* @param rowNum
* @param colNum
* @return
* @throws Exception
*/
@SuppressWarnings("deprecation")
public String readCell(int sheetIx, int rowNum, int colNum) throws Exception {
Sheet sheet = workbook.getSheetAt(sheetIx);
Row row = sheet.getRow(rowNum);
if (row == null) {
return null;
}
row.getCell(colNum).setCellType(Cell.CELL_TYPE_STRING);
Cell cell = row.getCell(colNum);
if (cell == null) {
return null;
}
return cell.getStringCellValue();
}
/**
*
* 將數(shù)據(jù)寫(xiě)入到 Excel 默認(rèn)第一頁(yè)中,從第1行開(kāi)始寫(xiě)入
*
* @param rowData 數(shù)據(jù)
* @return
* @throws IOException
*
*/
public boolean write(List<List<String>> rowData) throws IOException {
return write(0, rowData, 0);
}
/**
*
* 將數(shù)據(jù)寫(xiě)入到 Excel 新創(chuàng)建的 Sheet 頁(yè)
*
* @param rowData 數(shù)據(jù)
* @param sheetName 長(zhǎng)度為1-31,不能包含后面任一字符: :\ / ? * [ ]
* @return
* @throws IOException
*/
public boolean write(List<List<String>> rowData, String sheetName, boolean isNewSheet) throws IOException {
Sheet sheet = null;
if (isNewSheet) {
sheet = workbook.createSheet(sheetName);
} else {
sheet = workbook.createSheet();
}
int sheetIx = workbook.getSheetIndex(sheet);
return write(sheetIx, rowData, 0);
}
/**
*
* 將數(shù)據(jù)追加到sheet頁(yè)最后
*
* @param rowData 數(shù)據(jù)
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param isAppend 是否追加,true 追加,false 重置sheet再添加
* @return
* @throws IOException
*/
public boolean write(int sheetIx, List<List<String>> rowData, boolean isAppend) throws IOException {
if (isAppend) {
return write(sheetIx, rowData, getRowCount(sheetIx));
} else {// 清空再添加
clearSheet(sheetIx);
return write(sheetIx, rowData, 0);
}
}
/**
*
* 將數(shù)據(jù)寫(xiě)入到 Excel 指定 Sheet 頁(yè)指定開(kāi)始行中,指定行后面數(shù)據(jù)向后移動(dòng)
*
* @param rowData 數(shù)據(jù)
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param startRow 指定開(kāi)始行,從 0 開(kāi)始
* @return
* @throws IOException
*/
public boolean write(int sheetIx, List<List<String>> rowData, int startRow) throws IOException {
Sheet sheet = workbook.getSheetAt(sheetIx);
int dataSize = rowData.size();
if (getRowCount(sheetIx) > 0) {// 如果小于等于0,則一行都不存在
sheet.shiftRows(startRow, getRowCount(sheetIx), dataSize);
}
for (int i = 0; i < dataSize; i++) {
Row row = sheet.createRow(i + startRow);
for (int j = 0; j < rowData.get(i).size(); j++) {
Cell cell = row.createCell(j);
cell.setCellValue(rowData.get(i).get(j) + "");
}
}
return true;
}
/**
*
* 設(shè)置cell 樣式
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param colIndex 指定列,從 0 開(kāi)始
* @return
* @throws IOException
*/
public boolean setStyle(int sheetIx, int rowIndex, int colIndex, CellStyle style) throws IOException {
Sheet sheet = workbook.getSheetAt(sheetIx);
// sheet.autoSizeColumn(colIndex, true);// 設(shè)置列寬度自適應(yīng)
sheet.setColumnWidth(colIndex, 4000);
Cell cell = sheet.getRow(rowIndex).getCell(colIndex);
cell.setCellStyle(style);
return true;
}
/**
*
* 設(shè)置樣式
*
* @param type 1:標(biāo)題 2:第一行
* @return
*/
public CellStyle makeStyle(int type) {
CellStyle style = workbook.createCellStyle();
DataFormat format = workbook.createDataFormat();
style.setDataFormat(format.getFormat("@"));// // 內(nèi)容樣式 設(shè)置單元格內(nèi)容格式是文本
style.setAlignment(HorizontalAlignment.CENTER);// 內(nèi)容居中
// style.setBorderTop(CellStyle.BORDER_THIN);// 邊框樣式
// style.setBorderRight(CellStyle.BORDER_THIN);
// style.setBorderBottom(CellStyle.BORDER_THIN);
// style.setBorderLeft(CellStyle.BORDER_THIN);
Font font = workbook.createFont();// 文字樣式
if (type == 1) {
// style.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);//顏色樣式
// 前景顏色
// style.setFillBackgroundColor(HSSFColor.LIGHT_BLUE.index);//背景色
// style.setFillPattern(CellStyle.ALIGN_FILL);// 填充方式
font.setBold(true);
font.setFontHeight((short) 500);
}
if (type == 2) {
font.setBold(true);
font.setFontHeight((short) 300);
}
style.setFont(font);
return style;
}
/**
*
* 合并單元格
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param firstRow 開(kāi)始行
* @param lastRow 結(jié)束行
* @param firstCol 開(kāi)始列
* @param lastCol 結(jié)束列
*/
public void region(int sheetIx, int firstRow, int lastRow, int firstCol, int lastCol) {
Sheet sheet = workbook.getSheetAt(sheetIx);
sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
}
/**
*
* 指定行是否為空
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param rowIndex 指定開(kāi)始行,從 0 開(kāi)始
* @return true 不為空,false 不行為空
* @throws IOException
*/
public boolean isRowNull(int sheetIx, int rowIndex) throws IOException {
Sheet sheet = workbook.getSheetAt(sheetIx);
return sheet.getRow(rowIndex) == null;
}
/**
* 判斷行的內(nèi)容是否為空
*
* @return
*/
public boolean isRowEmpty(int sheetIx, int rowIndex) {
Row row = this.workbook.getSheetAt(sheetIx).getRow(rowIndex);
if (row != null) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getStringCellValue() != "" && cell.getCellTypeEnum() != CellType.BLANK)
return false;
}
}
return true;
}
/**
*
* 創(chuàng)建行,若行存在,則清空
*
* @param sheetIx 指定 sheet 頁(yè),從 0 開(kāi)始 指定創(chuàng)建行,從 0 開(kāi)始
* @return
* @throws IOException
*/
public boolean createRow(int sheetIx, int rowIndex) throws IOException {
Sheet sheet = workbook.getSheetAt(sheetIx);
sheet.createRow(rowIndex);
return true;
}
/**
*
* 指定單元格是否為空
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param rowIndex 指定開(kāi)始行,從 0 開(kāi)始
* @param colIndex 指定開(kāi)始列,從 0 開(kāi)始
* @return true 行不為空,false 行為空
* @throws IOException
*/
public boolean isCellNull(int sheetIx, int rowIndex, int colIndex) throws IOException {
Sheet sheet = workbook.getSheetAt(sheetIx);
if (!isRowNull(sheetIx, rowIndex)) {
return false;
}
Row row = sheet.getRow(rowIndex);
return row.getCell(colIndex) == null;
}
/**
*
* 創(chuàng)建單元格
*
* @param sheetIx 指定 sheet 頁(yè),從 0 開(kāi)始
* @param rowIndex 指定行,從 0 開(kāi)始
* @param colIndex 指定創(chuàng)建列,從 0 開(kāi)始
* @return true 列為空,false 行不為空
* @throws IOException
*/
public boolean createCell(int sheetIx, int rowIndex, int colIndex) throws IOException {
Sheet sheet = workbook.getSheetAt(sheetIx);
Row row = sheet.getRow(rowIndex);
row.createCell(colIndex);
return true;
}
/**
* 返回sheet 中的行數(shù)
*
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @return
*/
public int getRowCount(int sheetIx) {
Sheet sheet = workbook.getSheetAt(sheetIx);
if (sheet.getPhysicalNumberOfRows() == 0) {
return 0;
}
return sheet.getLastRowNum() + 1;
}
/**
* 獲取有數(shù)據(jù)的行數(shù)
*
* @param sheetIx
* @return
*/
public int getRealRowCount(int sheetIx) {
int rowCount = getRowCount(sheetIx);
int n = 0;
for (int i = 0; i < rowCount; i++) {
if (!isRowEmpty(sheetIx, i)) {
n++;
}
}
return n;
}
/**
*
* 返回所在行的列數(shù)
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param rowIndex 指定行,從0開(kāi)始
* @return 返回-1 表示所在行為空
*/
public int getColumnCount(int sheetIx, int rowIndex) {
Sheet sheet = workbook.getSheetAt(sheetIx);
Row row = sheet.getRow(rowIndex);
return row == null ? -1 : row.getLastCellNum();
}
/**
*
* 設(shè)置row 和 column 位置的單元格值
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param rowIndex 指定行,從0開(kāi)始
* @param colIndex 指定列,從0開(kāi)始
* @param value 值
* @return
* @throws IOException
*/
public boolean setValueAt(int sheetIx, int rowIndex, int colIndex, String value) throws IOException {
Sheet sheet = workbook.getSheetAt(sheetIx);
sheet.getRow(rowIndex).getCell(colIndex).setCellValue(value);
return true;
}
/**
*
* 返回 row 和 column 位置的單元格值
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param rowIndex 指定行,從0開(kāi)始
* @param colIndex 指定列,從0開(kāi)始
* @return
*
*/
public String getValueAt(int sheetIx, int rowIndex, int colIndex) {
Sheet sheet = workbook.getSheetAt(sheetIx);
return getCellValueToString(sheet.getRow(rowIndex).getCell(colIndex));
}
public String getCellValue(Cell cell) {
int cellType = cell.getCellType();
String cellValue = "";
switch (cellType) {
case HSSFCell.CELL_TYPE_NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
try {
cellValue = cell.getStringCellValue();
} catch (IllegalStateException e) {
cellValue = String.valueOf(cell.getNumericCellValue());
}
break;
default:
cellValue = cell.getStringCellValue();
}
return cellValue.trim();
}
/**
*
* 重置指定行的值
*
* @param rowData 數(shù)據(jù)
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param rowIndex 指定行,從0開(kāi)始
* @return
* @throws IOException
*/
public boolean setRowValue(int sheetIx, List<String> rowData, int rowIndex) throws IOException {
Sheet sheet = workbook.getSheetAt(sheetIx);
Row row = sheet.getRow(rowIndex);
for (int i = 0; i < rowData.size(); i++) {
row.getCell(i).setCellValue(rowData.get(i));
}
return true;
}
/**
*
* 返回指定行的值的集合
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param rowIndex 指定行,從0開(kāi)始
* @return
*/
public List<String> getRowValue(int sheetIx, int rowIndex) {
Sheet sheet = workbook.getSheetAt(sheetIx);
Row row = sheet.getRow(rowIndex);
List<String> list = new ArrayList<String>();
if (row == null) {
list.add(null);
} else {
for (int i = 0; i < row.getLastCellNum(); i++) {
list.add(getCellValueToString(row.getCell(i)));
}
}
return list;
}
/**
*
* 返回列的值的集合
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param rowFrom 從指定行數(shù)開(kāi)始
* @param colIndex 指定列,從0開(kāi)始
* @return
*/
public List<String> getColumnValue(int sheetIx, int rowFrom, int colIndex) {
Sheet sheet = workbook.getSheetAt(sheetIx);
List<String> list = new ArrayList<String>();
for (int i = rowFrom; i < getRowCount(sheetIx); i++) {
Row row = sheet.getRow(i);
if (row == null) {
list.add(null);
continue;
}
list.add(getCellValueToString(sheet.getRow(i).getCell(colIndex)));
}
return list;
}
/**
*
* 獲取excel 中sheet 總頁(yè)數(shù)
*
* @return
*/
public int getSheetCount() {
return workbook.getNumberOfSheets();
}
public void createSheet() {
workbook.createSheet();
}
/**
*
* 設(shè)置sheet名稱,長(zhǎng)度為1-31,不能包含后面任一字符: :\ / ? * [ ]
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始,//
* @param name
* @return
* @throws IOException
*/
public boolean setSheetName(int sheetIx, String name) throws IOException {
workbook.setSheetName(sheetIx, name);
return true;
}
/**
*
* 獲取 sheet名稱
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @return
* @throws IOException
*/
public String getSheetName(int sheetIx) throws IOException {
Sheet sheet = workbook.getSheetAt(sheetIx);
return sheet.getSheetName();
}
/**
* 獲取sheet的索引,從0開(kāi)始
*
* @param name sheet 名稱
* @return -1表示該未找到名稱對(duì)應(yīng)的sheet
*/
public int getSheetIndex(String name) {
return workbook.getSheetIndex(name);
}
/**
*
* 刪除指定sheet
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @return
* @throws IOException
*/
public boolean removeSheetAt(int sheetIx) throws IOException {
workbook.removeSheetAt(sheetIx);
return true;
}
/**
*
* 刪除指定sheet中行,改變?cè)撔兄笮械乃饕?
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @param rowIndex 指定行,從0開(kāi)始
* @return
* @throws IOException
*/
public boolean removeRow(int sheetIx, int rowIndex) throws IOException {
Sheet sheet = workbook.getSheetAt(sheetIx);
sheet.shiftRows(rowIndex + 1, getRowCount(sheetIx), -1);
Row row = sheet.getRow(getRowCount(sheetIx) - 1);
sheet.removeRow(row);
return true;
}
/**
*
* 設(shè)置sheet 頁(yè)的索引
*
* @param sheetname Sheet 名稱 Sheet 索引,從0開(kāi)始
*/
public void setSheetOrder(String sheetname, int sheetIx) {
workbook.setSheetOrder(sheetname, sheetIx);
}
/**
*
* 清空指定sheet頁(yè)(先刪除后添加并指定sheetIx)
*
* @param sheetIx 指定 Sheet 頁(yè),從 0 開(kāi)始
* @return
* @throws IOException
*/
public boolean clearSheet(int sheetIx) throws IOException {
String sheetname = getSheetName(sheetIx);
removeSheetAt(sheetIx);
workbook.createSheet(sheetname);
setSheetOrder(sheetname, sheetIx);
return true;
}
public Workbook getWorkbook() {
return workbook;
}
/**
*
* 關(guān)閉流
*
* @throws IOException
*/
public void close() throws IOException {
if (os != null) {
os.close();
}
workbook.close();
}
/**
*
* 轉(zhuǎn)換單元格的類型為String 默認(rèn)的 <br>
* 默認(rèn)的數(shù)據(jù)類型:CELL_TYPE_BLANK(3), CELL_TYPE_BOOLEAN(4),
* CELL_TYPE_ERROR(5),CELL_TYPE_FORMULA(2), CELL_TYPE_NUMERIC(0),
* CELL_TYPE_STRING(1)
*
* @param cell
* @return
*
*/
@SuppressWarnings("deprecation")
private String getCellValueToString(Cell cell) {
String strCell = "";
if (cell == null) {
return null;
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
strCell = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (pattern != null) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
strCell = sdf.format(date);
} else {
strCell = date.toString();
}
break;
}
// 不是日期格式,則防止當(dāng)數(shù)字過(guò)長(zhǎng)時(shí)以科學(xué)計(jì)數(shù)法顯示
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
strCell = cell.toString();
break;
case Cell.CELL_TYPE_STRING:
strCell = cell.getStringCellValue();
break;
default:
break;
}
return strCell;
}
/**
* 獲取cell
*
* @param sheetId
* @param rowId
* @param colId
* @return
* @author zgd
* @time 2018年6月27日14:54:53
*/
public Cell getCell(int sheetId, int rowId, int colId) {
Sheet sheet = workbook.getSheetAt(sheetId);
Row row = sheet.getRow(rowId);
if (row == null) {
return null;
}
return row.getCell(colId);
}
/**
* 前景色是否為空,是否沒(méi)有填充任何顏色
*
* @return
* @author zgd
* @time 2018年6月27日14:54:53
*/
public boolean isForeColorEmpty(int sheetId, int rowId, int colId) {
if (this.workbook instanceof HSSFWorkbook) {
HSSFCell cell = (HSSFCell) getCell(sheetId, rowId, colId);
HSSFColor color = cell.getCellStyle().getFillForegroundColorColor();
return "0:0:0".equals(color.getHexString());
}
if (this.workbook instanceof XSSFWorkbook) {
XSSFCell cell = (XSSFCell) getCell(sheetId, rowId, colId);
if (cell != null) {
XSSFColor color = cell.getCellStyle().getFillForegroundColorColor();
return color == null;
}
}
return true;
}
/**
* 設(shè)置列寬
*
* @param sheetId sheet的索引
* @param mxiWidthRow 確保最小值列寬的行
* @param colb 從哪一列開(kāi)始設(shè)置
* @param cole 到哪一行結(jié)束
* @author zgd
* @time 2018年6月27日14:54:53
*/
public void setColumnWidth(Sheet sheet, Row mxiWidthRow, int sheetId, int colb, int cole) {
// 設(shè)置列寬
for (int i = colb; i <= cole; i++) {
int length = 0;
if (mxiWidthRow.getCell(i) != null && !StringUtils.isEmpty(mxiWidthRow.getCell(i).getStringCellValue())) {
length = mxiWidthRow.getCell(i).getStringCellValue().trim().getBytes().length * 256 + 200;
}
List<String> columnValue = this.getColumnValue(sheetId, 0, i);
for (String s : columnValue) {
if (s != null) {
int l = s.trim().getBytes().length * 256 + 200;
length = Math.max(l, length);
}
}
if (length > 15000) {
length = 15000;
}
sheet.setColumnWidth(i, length);
}
}
} 導(dǎo)入數(shù)據(jù)庫(kù)表格數(shù)據(jù)如下:
| Idx | Tunnel_left_ZDK | Tunnel_right_ZDK | is_tunnel |
| 1 | DK2291.416 | DK0 | 是 |
| 2 | DK7389.65 | DK2291.416 | 否 |
| 3 | ZK2277 | ZK0 | 是 |
| 4 | ZK5235.68 | ZK2277 | 否 |
以上就是利用java的反射機(jī)制讀取excel表格數(shù)據(jù)的方法,看完之后是否有所收獲呢?如果想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊!
名稱欄目:如何利用java的反射機(jī)制讀取excel表格數(shù)據(jù)
文章網(wǎng)址:http://chinadenli.net/article12/gsjsgc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、定制網(wǎng)站、網(wǎng)站制作、服務(wù)器托管、網(wǎng)站改版、網(wǎng)站設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)