Skip to content

Instantly share code, notes, and snippets.

@hishidama
Last active August 29, 2015 14:07
Show Gist options
  • Save hishidama/fd4843f3ceaa12f3aa0f to your computer and use it in GitHub Desktop.
Save hishidama/fd4843f3ceaa12f3aa0f to your computer and use it in GitHub Desktop.
poi-3.10-FINAL remove sheet bug
package example;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellUtil;
// poi-3.10-FINAL
// 自分より右側のシートを参照する数式を設定し、自分より左側のシートを削除すると、数式が壊れる。
public class FormulaRemoveSheet {
private static final String FILE = "D:/tmp/poi-formula-removeSheet.xls";
public static void main(String... args) throws Exception {
write();
read();
}
static void write() throws IOException {
Workbook workbook = new HSSFWorkbook();
Sheet sheet1 = workbook.createSheet("sheet1");
Sheet sheet2 = workbook.createSheet("sheet2");
Sheet sheet3 = workbook.createSheet("sheet3");
Cell cell = CellUtil.getCell(CellUtil.getRow(0, sheet2), 0);
cell.setCellFormula("sheet3!A1");
System.out.println(cell.getCellFormula()); // sheet3!A1
workbook.removeSheetAt(workbook.getSheetIndex(sheet1));
System.out.println(cell.getCellFormula()); // #REF!A1
try (FileOutputStream fos = new FileOutputStream(FILE)) {
workbook.write(fos);
}
}
static void read() throws InvalidFormatException, IOException {
Workbook workbook = WorkbookFactory.create(new File(FILE));
Sheet sheet2 = workbook.getSheet("sheet2");
Cell cell = CellUtil.getCell(CellUtil.getRow(0, sheet2), 0);
System.out.println(cell.getCellFormula()); // #REF!A1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment