热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Excel文件上传与数据处理

本文介绍了如何通过Java代码实现Excel文件的上传,并将其中的数据读取后存储到数据库中。同时,记录了操作日志以确保操作的可追溯性。

本文档描述了一个Java类,用于处理Excel文件的上传和数据解析,最终将数据保存至数据库。此过程包括创建临时文件夹、检查文件格式、读取Excel数据并进行数据库操作等步骤。

### 类定义

public class ExcelUploadHandler extends BaseAction {
// 记录操作日志
private static final String LOG_TRANSACTION_CODE = "TXN_DOC_0021";
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
String tempFolderPath = "D:/temp";
createTempDirectory(tempFolderPath);
String tempFilePath = "D:/temp/temp.xls";
FileOutputStream fileOutputStream = new FileOutputStream(tempFilePath);
ExcelUploadForm uploadForm = (ExcelUploadForm) form;
FormFile uploadedFile = uploadForm.getExcelFile();
String fileName = uploadedFile.getFileName();
if (fileName != null && !fileName.isEmpty()) {
String fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
if (!"xls".equalsIgnoreCase(fileExtension)) {
throw new IllegalArgumentException("Please select an .xls file.");
}
fileOutputStream.write(uploadedFile.getFileData());
fileOutputStream.flush();
fileOutputStream.close();
parseAndSaveData(tempFilePath, request);
deleteFile(tempFilePath);
deleteDirectory(tempFolderPath);
request.setAttribute("txnStatus", "SUCCESS");
request.setAttribute("message", getLogMessage(LOG_TRANSACTION_CODE, "SUCCESS"));
request.setAttribute("backUrl", request.getContextPath() + mapping.getInputForward().getPath());
logSuccess(getLogMessage(LOG_TRANSACTION_CODE, "SUCCESS"));
return mapping.findForward("success");
} else {
throw new IllegalArgumentException("No file selected for upload.");
}
} catch (Exception e) {
logError(getLogMessage(LOG_TRANSACTION_CODE, "FAILURE"), e);
request.setAttribute("txnStatus", "FAILURE");
request.setAttribute("errorMessage", getLogMessage(LOG_TRANSACTION_CODE, "FAILURE"));
request.setAttribute("error", "An unknown error occurred during the upload. Please contact the system administrator!");
return mapping.getInputForward();
}
}

### 辅助方法

private void logSuccess(String message) {
LOG.info("Operation completed successfully: " + message);
}
private void logError(String message, Throwable cause) {
LOG.error("Operation failed: " + message, cause);
}
private String getLogMessage(String transactionCode, String status) {
return RescodeMapping.getRescodeDesc(transactionCode, status);
}
private void createTempDirectory(String path) throws IOException {
File directory = new File(path);
if (!directory.exists()) {
if (!directory.mkdirs()) {
throw new IOException("Failed to create directory: " + path);
}
}
}
private void deleteFile(String filePath) throws IOException {
File file = new File(filePath);
if (file.exists() && !file.delete()) {
throw new IOException("Failed to delete file: " + filePath);
}
}
private void deleteDirectory(String dirPath) throws IOException {
deleteFile(dirPath);
File directory = new File(dirPath);
if (directory.exists() && !directory.delete()) {
throw new IOException("Failed to delete directory: " + dirPath);
}
}
private void parseAndSaveData(String filePath, HttpServletRequest request) throws IOException, BiffException {
FileInputStream inputStream = new FileInputStream(filePath);
Workbook workbook = Workbook.getWorkbook(inputStream);
Sheet sheet = workbook.getSheet(0);
int rowCount = sheet.getRows();
String currentOperatorId = UserSessionInfoUtils.getUserSessionInfo(request.getSession()).getOperatorId();
TPayformDAO payformDAO = (TPayformDAO) ContextUtil.getBean("TPayformDAO");
for (int i = 1; i TPayform payform = new TPayform();
Cell[] rowCells = sheet.getRow(i);
if (rowCells.length >= 1) {
payform.setClasscode(rowCells[0].getContents());
} else {
throw new IndexOutOfBoundsException("Row does not contain enough data.");
}
if (rowCells.length >= 2) {
payform.setComputeWay(rowCells[1].getContents());
} else {
throw new IndexOutOfBoundsException("Row does not contain enough data.");
}
payform.setAge(new BigDecimal(rowCells[2].getContents()));
payform.setSex(rowCells[3].getContents());
payform.setSingle(new BigDecimal(rowCells[4].getContents()));
// ... (继续设置其他属性)
payformDAO.insert(payform);
}
workbook.close();
inputStream.close();
}

推荐阅读
author-avatar
asgvbsd
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有