import java.io.*;
import java.util.*;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.*;
import javax.annotation.Resource;
public class ExcelImport {
public void eximport() throws IOException {
String fileName = "D:/Project/读入文档.xlsx";
File targetFile = new File(fileName);
if(!targetFile.exists()){
//log.info("指定文件不存在");
}
//读入excel文件
InputStream ips = new FileInputStream(targetFile);
Workbook workbook=null;
List<List<Object>> list = new LinkedList<>();
try{
workbook= WorkbookFactory.create(ips);
Sheet sheet = workbook.getSheetAt(0);//ecxel获取的第一个表单sheet
for(Row row:sheet){//从第一行开始
List<Object> linked = new LinkedList<>();
for(Cell cell:row){//excel从每个单元格遍历的
linked.add(new DataFormatter().formatCellValue(cell));
}
list.add(linked);
}
//此时文件输入流里面有list对象[[xx,xx,xx],[xx,xx,xx],[xx,xx,xx],[xx,xx,xx] ]
String fileName2 = "D:/Project/新文档.xlsx";//要存的地址
File targetFile2 = new File(fileName2);
targetFile2.createNewFile();//新建一个文件
Sheet sheet1 = workbook.createSheet("data");
Row firstRow = sheet.createRow(0);
int i = 0;
for (List data : list) {
Row row = sheet.createRow(i);//建立第一行
for (int j = 0; j <list.get(0).size(); j++) {//从列开始读
Object obj = data.get(j);
row.createCell(j).setCellValue(obj != null ? obj.toString() : "");//写入值可以自己设置
//for循环是为了方便直接读输入流内容,可以按需要设置写入值
}
i++;
}
FileOutputStream stream= FileUtils.openOutputStream(targetFile2);
//此时文件输出流里面有list对象[[xx,xx,xx],[xx,xx,xx],[xx,xx,xx],[xx,xx,xx] ]
workbook.write(stream);
stream.close();
}catch (Exception e){
//log.info("打开EXCEL文件流失败!e:{}", e);
}
return;
}
public static void main(String[] args) throws IOException {
ExcelImport ff = new ExcelImport();
ff.eximport();
}
}