java导入excel文件校验,将错误的数据标红并下载的代码
时间: 2024-02-05 13:11:13 浏览: 186
以下是使用Apache POI库实现java导入excel文件校验,将错误的数据标红并下载的代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class ExcelImportValidate {
public static void main(String[] args) {
String filePath = "D:\\test.xls"; //excel文件路径
String sheetName = "Sheet1"; //excel文件中Sheet的名称
int startRow = 1; //数据开始行号(第一行为0),这里是从第二行开始读取数据
List<ExcelData> dataList = readExcel(filePath, sheetName, startRow); //读取excel数据
for (ExcelData data : dataList) { //对数据进行校验
if (!validateData(data)) {
data.setError(true);
}
}
String[] headers = new String[] {"姓名", "年龄", "性别", "电话号码", "邮箱"}; //表头
String[] fields = new String[] {"name", "age", "gender", "phone", "email"}; //数据字段名
int[] columnWidths = new int[] {20, 10, 10, 20, 30}; //列宽
writeExcel(filePath, sheetName, headers, fields, columnWidths, dataList); //将校验结果写入excel文件,并标红有错误的数据
}
/**
* 读取excel文件中的数据
*
* @param filePath excel文件路径
* @param sheetName sheet名称
* @param startRow 数据开始行号
* @return 数据列表
*/
public static List<ExcelData> readExcel(String filePath, String sheetName, int startRow) {
List<ExcelData> dataList = new ArrayList<>();
FileInputStream fis = null;
Workbook workbook = null;
try {
fis = new FileInputStream(filePath);
workbook = new HSSFWorkbook(fis);
Sheet sheet = workbook.getSheet(sheetName);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
DataFormatter formatter = new DataFormatter();
for (int i = startRow; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
ExcelData data = new ExcelData();
data.setRowIndex(i + 1);
for (int j = 0; j < row.getLastCellNum(); j++) {
CellValue cellValue = evaluator.evaluate(sheet.getRow(i).getCell(j));
String value = formatter.formatCellValue(cellValue);
switch (j) {
case 0: //姓名
data.setName(value);
break;
case 1: //年龄
data.setAge(Integer.parseInt(value));
break;
case 2: //性别
data.setGender(value);
break;
case 3: //电话号码
data.setPhone(value);
break;
case 4: //邮箱
data.setEmail(value);
break;
}
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (workbook != null) {
workbook.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return dataList;
}
/**
* 校验数据是否合法
*
* @param data 数据对象
* @return true:数据合法;false:数据不合法
*/
public static boolean validateData(ExcelData data) {
if (data.getName() == null || data.getName().trim().length() == 0) {
return false;
}
if (data.getAge() == null || data.getAge() < 0 || data.getAge() > 200) {
return false;
}
if (data.getGender() == null || (!data.getGender().equals("男") && !data.getGender().equals("女"))) {
return false;
}
if (data.getPhone() == null || !data.getPhone().matches("^1[3|4|5|7|8]\\d{9}$")) {
return false;
}
if (data.getEmail() == null || !data.getEmail().matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
return false;
}
return true;
}
/**
* 将校验结果写入excel文件,并标红有错误的数据
*
* @param filePath excel文件路径
* @param sheetName sheet名称
* @param headers 表头
* @param fields 数据字段名
* @param columnWidths 列宽
* @param dataList 数据列表
*/
public static void writeExcel(String filePath, String sheetName, String[] headers, String[] fields, int[] columnWidths, List<ExcelData> dataList) {
FileOutputStream fos = null;
Workbook workbook = null;
try {
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(file);
workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet) workbook.createSheet(sheetName);
HSSFRow row = sheet.createRow(0);
HSSFCellStyle style = (HSSFCellStyle) workbook.createCellStyle();
style.setFillForegroundColor((short) 10);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellType(CellType.STRING);
cell.setCellValue(headers[i]);
if (columnWidths != null && columnWidths.length > i) {
sheet.setColumnWidth(i, columnWidths[i] * 256);
} else {
sheet.autoSizeColumn(i);
}
}
for (int i = 0; i < dataList.size(); i++) {
ExcelData data = dataList.get(i);
row = sheet.createRow(i + 1);
for (int j = 0; j < fields.length; j++) {
HSSFCell cell = row.createCell(j);
cell.setCellType(CellType.STRING);
cell.setCellValue(data.getFieldValue(fields[j]));
if (data.isError()) {
cell.setCellStyle(style);
}
}
}
workbook.write(fos);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (workbook != null) {
workbook.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码中,ExcelData类表示excel中的一行数据,其中包含了姓名、年龄、性别、电话号码和邮箱等字段。代码中的readExcel方法用于读取excel文件中的数据,validateData方法用于校验数据是否合法,writeExcel方法用于将校验结果写入excel文件,并标红有错误的数据。
以上代码仅供参考,具体实现可根据实际需求进行修改。
阅读全文