1、在pom添加相关依赖
<!--poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
2、使用Junit编写一个单元测试
@SpringBootTest(classes = StartApp.class)
@RunWith(SpringRunner.class)
public class TestMeterInfoController {
@Test
public void excelImport() throws IOException, ParseException {
// 创建对Excel工作簿文件的引用
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream("D:\\data_doc\\data.xls"));
// 创建对工作表的引用。
// 用getSheetAt(int index)按索引引用,
// 在Excel文档中,第一张工作表的缺省索引是0,
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.RED.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
// 获取行数
Row row = sheet.getRow(i);
// 获取单元格 取值
String cell1Value= row.getCell(0).getStringCellValue();
String cell2Value = row.getCell(1).getStringCellValue();
String cell5Value = row.getCell(4).getStringCellValue();
String cell7Value = row.getCell(6).getStringCellValue();
// 设置当前行指定列索引的单元格样式
// row.getCell(1).setCellStyle(style);
// 设置当前行指定列索引的单元格值
row.getCell(1).setCellValue("9999999");
// 删除指定行
// sheet.shiftRows(i,sheet.getLastRowNum(),-1);
//7.写⼊到硬盘
//7.1创建流
FileOutputStream os = new FileOutputStream("D:\\data_doc\\outdata.xls");
//7.2将wb的内容写⼊字符流中
workbook.write(os);
//7.3关流
os.flush();
os.close();
}
}
}