ExcelUtils工具类
package com.example.demo.utils;
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.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
private static final String EXCEL_XLS = "xls";
private static final String EXCEL_XLSX = "xlsx";
public static Workbook getWorkbok(File file) throws IOException{
Workbook wb = null;
FileInputStream in = new FileInputStream(file);
if(file.getName().endsWith(EXCEL_XLS)){ //Excel 2003
wb = new HSSFWorkbook(in);
}else if(file.getName().endsWith(EXCEL_XLSX)){ // Excel 2007/2010
wb = new XSSFWorkbook(in);
}
return wb;
}
public static void writeExcel(int row,String filePath) {
try {
File file = new File(filePath);
Workbook workbook = getWorkbok(file);
Sheet sheet = workbook.getSheetAt(0);
Row r = sheet.getRow(row); //获取当前开过户的信息的行数
r.createCell(2).setCellValue(1);//在该行的第三个数据格写入1作为标记
FileOutputStream out = new FileOutputStream(file);//输出
out.flush();
workbook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static List readExcel( String filePath) {
File file = new File(filePath);
Workbook workbook = null;
try {
workbook = getWorkbok(file);
} catch (IOException e) {
e.printStackTrace();
}
Sheet sheet = workbook.getSheetAt(0);//操作第一个sheet
int rows = sheet.getLastRowNum() + 1;//获取总共的行数
Row tmp = sheet.getRow(0);//获取第0行所以第0行要加上isOpenAccount来使程序读取为每行三列,否则无法读取写入的1
int cols = tmp.getPhysicalNumberOfCells();//获取第0行的列数
for (int row = 1; row < rows; row++){//循环所有行
List columnList = new ArrayList();//用list 数据按照添加的顺序放置
columnList.add(row);//先放当前的行数,第几行,用columnList.get(0); 获取
Row r = sheet.getRow(row);
for (int col = 0; col < cols; col++){//循环列,把当前行的所有数据放到columnList中
if (null != r && null != r.getCell(col)) {//行不为空(此行没有任何信息)时并且列不为空
r.getCell(col).setCellType(Cell.CELL_TYPE_STRING);//转换为String
columnList.add(r.getCell(col).getStringCellValue());//把当前行当前列的数据放到columnList中
}
}
//如果当前列的数据大小为3(列数,ATMNo,IDNo3个)返回,其他情况大小为1(只有列数)
// 或者大小为4(列数,ATMNo,IDNo,1(已经开过户后写入的1,作为标记))不返回继续循环
if (columnList.size() == 3) {
return columnList;
}
}
return null;
}
}
测试ExcelUtils
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDemoApplicationTests {
//filePath和accountList(起其他名字也可以)必须为全局变量
String filePath = "C:\\Users\\dz\\Desktop\\a.xlsx";
List accountInfolist = ExcelUtils.readExcel(filePath);
@Test
public void readExcel() {
String ATMNo = (String) accountInfolist.get(1);//获取ATMNo
String IDNo = (String) accountInfolist.get(2);//获取IDNo
System.out.println(ATMNo+" "+IDNo);
}
@Test
public void writeExcel() {
ExcelUtils.writeExcel((int) accountInfolist.get(0), filePath);
}
}
Excel格式 加上isOpenAccount或者其他任何名字