多个EXCEL文件 读取:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
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.ss.usermodel.WorkbookFactory;
public class ExcelReader {
private File source;
private int startRowIndex;
private int startColIndex;
private final String SEPARATE = "\002";
public ExcelReader(String path, int startRowIndex, int startColIndex) {
this.source = new File(path);
this.startColIndex = startColIndex;
this.startRowIndex = startRowIndex;
}
public void readAndWrite(String dstPath) throws Exception {
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(dstPath), Charset.forName("utf-8")));
read(this.source, bw);
bw.close();
}
@SuppressWarnings("deprecation")
private void read(File file, BufferedWriter bw) throws Exception {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
read(f, bw);
}
} else {
System.out.println(file.getPath());
Workbook wb = WorkbookFactory.create(new FileInputStream(file));
Sheet sheet = wb.getSheetAt(0);
int rowIndex = this.startRowIndex;
Row row;
Cell cell;
String value = "";
StringBuffer line;
CellType celltype;
boolean flag = false;
while (true) {
row = sheet.getRow(rowIndex);
if (row != null) {
line = new StringBuffer();
for (int i = 0; i < 26; i++) {
cell = row.getCell(i);
if (cell != null) {
celltype = cell.getCellTypeEnum();
if (celltype == CellType.NUMERIC) {
value = Double.toString(cell.getNumericCellValue());
} else if (celltype == CellType.STRING) {
value = cell.getStringCellValue();
if (value.equals("c5a9f751b36e0a111d0e4b819278d7a5f1")) {
@SuppressWarnings("unused")
int a = 0;
}
} else {
value = "";
}
} else {
value = "";
}
if (i == 0 && value.trim().equals("")) {
flag = true;
break;
}
value = value.replace("\r\n", " ").replace("\n\r", " ").replace("\r", " ").replace("\n", " ")
.replace(SEPARATE, " ");
line.append(value);
if (i != 25) {
line.append(SEPARATE);
}
}
if (line.toString().split(SEPARATE).length == 26) {
bw.write(line.toString());
bw.newLine();
} else {
throw new Exception("size:" + line.toString().split(SEPARATE).length + ", " + line.toString());
}
rowIndex++;
} else {
break;
}
if (flag) {
break;
}
}
wb.close();
}
}
}