java 读取 3124xlsx excel文件 CUsers25346Desktop3124xlsx 表格第一行为列名第一列是 CardID 和 第二列是 AttenDatatime 生成ListCardAttenDence cardAttenDenceList = new ArrayList; 其中CardID列的值是16进制的数字AttenDatatime列的值是yyyy-mm-dd
你可以使用Apache POI库来读取Excel文件。下面是一个例子,演示如何读取并解析Excel文件中的数据:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExcelReader {
public static void main(String[] args) {
String filePath = "C:\\Users\\25346\\Desktop\\3124.xlsx";
List<CardAttenDence> cardAttenDenceList = readExcel(filePath);
// 在这里可以使用 cardAttenDenceList 进行后续操作
for (CardAttenDence cardAttenDence : cardAttenDenceList) {
System.out.println(cardAttenDence);
}
}
public static List<CardAttenDence> readExcel(String filePath) {
List<CardAttenDence> cardAttenDenceList = new ArrayList<>();
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis)) {
Sheet sheet = workbook.getSheetAt(0);
Row firstRow = sheet.getRow(0);
int cardIdColumnIndex = -1;
int attenDatatimeColumnIndex = -1;
// 找到 CardID 和 AttenDatatime 列的索引
for (Cell cell : firstRow) {
String cellValue = cell.getStringCellValue();
if (cellValue.equalsIgnoreCase("CardID")) {
cardIdColumnIndex = cell.getColumnIndex();
} else if (cellValue.equalsIgnoreCase("AttenDatatime")) {
attenDatatimeColumnIndex = cell.getColumnIndex();
}
}
if (cardIdColumnIndex == -1 || attenDatatimeColumnIndex == -1) {
throw new IllegalArgumentException("列名未找到");
}
// 从第二行开始读取数据
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
String cardId = row.getCell(cardIdColumnIndex).getStringCellValue();
String attenDatatime = row.getCell(attenDatatimeColumnIndex).getStringCellValue();
cardAttenDenceList.add(new CardAttenDence(cardId, attenDatatime));
}
} catch (IOException e) {
e.printStackTrace();
}
return cardAttenDenceList;
}
static class CardAttenDence {
private String cardId;
private String attenDatatime;
public CardAttenDence(String cardId, String attenDatatime) {
this.cardId = cardId;
this.attenDatatime = attenDatatime;
}
public String getCardId() {
return cardId;
}
public String getAttenDatatime() {
return attenDatatime;
}
@Override
public String toString() {
return "CardAttenDence{" +
"cardId='" + cardId + '\'' +
", attenDatatime='" + attenDatatime + '\'' +
'}';
}
}
}
注意,上述代码中使用的是XSSFWorkbook类,适用于读取.xlsx格式的Excel文件。如果要读取.xls格式的文件,你需要使用HSSFWorkbook类
原文地址: http://www.cveoy.top/t/topic/h1WK 著作权归作者所有。请勿转载和采集!