Java导出Excel和读取Excel
@Override
public List<String> readExcel(String fileName,int sheet) throws IOException {
List result = new ArrayList();
InputStream is = new FileInputStream(new File(fileName));
Workbook hssfWorkbook = null;
if (fileName.endsWith("xlsx")) {
hssfWorkbook = new XSSFWorkbook(is);//Excel 2007
} else if (fileName.endsWith("xls")) {
hssfWorkbook = new HSSFWorkbook(is);//Excel 2003
}
Sheet hssfSheet = hssfWorkbook.getSheetAt(sheet);
for (int rowNum = 0; rowNum < hssfSheet.getLastRowNum(); rowNum++) {
Row hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow != null) {
String[] arr = new String[hssfRow.getLastCellNum()];
for(int cellNum = 0 ; cellNum < hssfRow.getLastCellNum() ; cellNum++){
try {
arr[cellNum] = hssfRow.getCell(cellNum).toString();
}catch (Exception e){
arr[cellNum] = "";
continue;
}
}
result.add(arr);
}
}
return result;
}
@Override
public void exportExcel(String fileName,String sheetName,List<String[]> result) throws IOException {
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet = null;
if(sheetName == null){
sheet = workbook.createSheet();
}
sheet = workbook.createSheet(sheetName);
for(int rowIndex = 0 ; rowIndex < result.size() ; rowIndex ++){
HSSFRow row = sheet.createRow(rowIndex);
String[] cellInfo = result.get(rowIndex);
for(int cellIndex = 0 ; cellIndex < cellInfo.length ; cellIndex ++){
HSSFCell cell = row.createCell(cellIndex);
cell.setCellValue(cellInfo[cellIndex]);
}
}
FileOutputStream outputStream = new FileOutputStream(fileName);
workbook.write(outputStream);
outputStream.close();
}
测试


来源:CSDN
作者:小赖丶
链接:https://blog.csdn.net/qq_33038901/article/details/103858535