Excelファイル比較サンプル
package net.tianyu.study.poi;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
public class DiffXls {
private static final int MAX_LINES = 3000;
private static final short DIFF_COLOR = IndexedColors.BLUE.getIndex();
private HSSFWorkbook wb1;
private HSSFSheet sheet1;
private HSSFWorkbook wb2;
private HSSFSheet sheet2;
private FileInputStream diff1In = null;
private FileInputStream diff2In = null;
private FileOutputStream out = null;
public void open(String input1FileName, String input2FileName, String outputFileName) throws IOException {
diff1In = new FileInputStream(input1FileName);
diff2In = new FileInputStream(input2FileName);
out = new FileOutputStream(outputFileName);
POIFSFileSystem filein = new POIFSFileSystem(diff1In);
wb1 = new HSSFWorkbook(filein);
filein = new POIFSFileSystem(diff2In);
wb2 = new HSSFWorkbook(filein);
}
public void run() throws IOException {
int countSheet = wb1.getNumberOfSheets();
for (int k = 0; k < countSheet; k++) {
sheet1 = wb1.getSheetAt(k);
sheet2 = wb2.getSheetAt(k);
for (int i = 4; i < MAX_LINES; i++) {
HSSFRow row1 = sheet1.getRow(i);
HSSFRow row2 = sheet2.getRow(i);
if (row1 == null || row2 == null) {
continue;
}
for (int j = 3; j < MAX_LINES; j++) {
HSSFCell cell1 = row1.getCell(j);
HSSFCell cell2 = row2.getCell(j);
if (cell1 == null || cell2 == null) {
continue;
}
String value1 = getCellValue(cell1);
String value2 = getCellValue(cell2);
if (value1 == null && value2 == null) {
continue;
}
if (value1 == null && value2 != null) {
setCellColor(cell1, DIFF_COLOR);
}
else if (value1 != null && value2 == null) {
setCellColor(cell1, DIFF_COLOR);
}
else if (!value1.equals(value2)) {
setCellColor(cell1, DIFF_COLOR);
}
}
}
}
wb1.write(out);
}
public void close() throws IOException {
out.close();
diff1In.close();
}
private String getCellValue(HSSFCell cell) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
}
else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
return Double.toString(cell.getNumericCellValue());
}
return null;
}
private void setCellColor(HSSFCell cell, short color) {
CellStyle style = wb1.createCellStyle();
style.cloneStyleFrom(cell.getCellStyle());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(color);
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBorderTop(CellStyle.BORDER_THIN);
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setBorderRight(CellStyle.BORDER_THIN);
cell.setCellStyle(style);
}
}