Java 读取 Excel 文件:解析 3124.xlsx 并转换数据格式
以下是读取Excel文件并转换数据格式的示例代码:
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public static void main(String[] args) {
String filePath = "C:\\Users\\25346\\Desktop\\3124.xlsx";
List<CardAttenDence> cardAttenDenceList = readExcel(filePath);
for (CardAttenDence cardAttenDence : cardAttenDenceList) {
System.out.println("CardID: " + cardAttenDence.getCardID());
System.out.println("AttenDatatime: " + cardAttenDence.getAttenDatatime());
System.out.println();
}
}
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 headerRow = sheet.getRow(0);
int cardIDColumnIndex = -1;
int attenDatatimeColumnIndex = -1;
for (Cell cell : headerRow) {
String columnName = cell.getStringCellValue().trim();
if (columnName.equalsIgnoreCase("CardID")) {
cardIDColumnIndex = cell.getColumnIndex();
} else if (columnName.equalsIgnoreCase("AttenDatatime")) {
attenDatatimeColumnIndex = cell.getColumnIndex();
}
}
if (cardIDColumnIndex == -1 || attenDatatimeColumnIndex == -1) {
throw new IllegalArgumentException("Invalid column name");
}
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
Cell cardIDCell = row.getCell(cardIDColumnIndex);
Cell attenDatatimeCell = row.getCell(attenDatatimeColumnIndex);
String cardID = readCellValueAsString(cardIDCell);
String attenDatatime = readCellValueAsString(attenDatatimeCell);
cardAttenDenceList.add(new CardAttenDence(cardID, attenDatatime));
}
} catch (IOException e) {
e.printStackTrace();
}
return cardAttenDenceList;
}
public static String readCellValueAsString(Cell cell) {
if (cell == null) {
return "";
}
if (cell.getCellType() == CellType.STRING) {
return cell.getStringCellValue().trim();
} else if (cell.getCellType() == CellType.NUMERIC) {
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.format(date);
} else {
return String.valueOf((int) cell.getNumericCellValue());
}
} else {
return "";
}
}
}
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;
}
}
请注意,此示例假定您已经添加了 Apache POI 库以处理 Excel 文件。
原文地址: https://www.cveoy.top/t/topic/pK0n 著作权归作者所有。请勿转载和采集!