主程序
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class App {
public static void main(String[] args) throws Exception {
String dir = args[0];
int skipBefore = Integer.parseInt(args[1]);
int skipAfter = Integer.parseInt(args[2]);
List<List<Object>> table = new ArrayList<>();
File file=new File(dir);
File[] files = file.listFiles();
for(int i=0;i<files.length;i++)
table.addAll(fileToList(skipBefore, skipAfter, files[i].getAbsolutePath()));
if(dir.endsWith("/"))
write(table,dir+"final.xls");
else
write(table,dir+"/final.xls");
}
public static List<List<Object>> fileToList(int skipBefore, int skipAfter, String filePath) throws Exception {
List<List<Object>> table = new ArrayList<List<Object>>();
File file = new File(filePath);
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(poifsFileSystem);
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
int rowstart = hssfSheet.getFirstRowNum();
int rowEnd = hssfSheet.getLastRowNum();
System.out.println(rowstart);
System.out.println(rowEnd);
for(int i=rowstart;i<=rowEnd;i++)
{
if(i < skipBefore)
continue;
if(i > rowEnd-skipAfter)
continue;
List<Object> line = new ArrayList<>();
HSSFRow row = hssfSheet.getRow(i);
if(null == row) continue;
int cellStart = row.getFirstCellNum();
int cellEnd = row.getLastCellNum();
for(int k=cellStart;k<=cellEnd;k++)
{
HSSFCell cell = row.getCell(k);
if(null==cell) {
line.add(null);
continue;
}
switch (cell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
line.add(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
line.add(cell.getStringCellValue());
break;
default:
System.out.print("未知类型 ");
break;
}
}
table.add(line);
}
return table;
}
public static void write(List<List<Object>> table, String outputFile) throws Exception {
HSSFWorkbook wb = new HSSFWorkbook();
//创建一个张表
Sheet sheet = wb.createSheet();
//创建第一行
int rowNum = 0;
for(List<Object> rowValues : table){
Row row = sheet.createRow(rowNum);
int columnNum = 0;
for(Object value : rowValues){
Cell cell = row.createCell(columnNum);
// System.out.println(value.getClass().toString());
if(value instanceof String)
cell.setCellValue((String) value);
if(value instanceof Double)
cell.setCellValue((Double) value);
columnNum ++;
}
rowNum ++;
}
FileOutputStream os = new FileOutputStream(outputFile);
wb.write(os);
os.close();
}
}
pom.xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>