I am Trying to create Excel files with tables that cointain certain values. The problem is that Java creates CORRUPTED Excel File (.xlsx, .xlsm) no matter what I do.
Changing name of the EXISTING table's column - File is corrupted, can't open it without repairing it. Name is changed but the file must be repaired for some reason. Creating new Tables or creating new Columns to existing Tables seems to corrupt files but I don't know why.
This is my whole code:
package pl.TiHerbatka.Ti.ExcelWriteReadTi.Main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFTableColumn;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Main {
public static void main(String[] args) throws InvalidFormatException, IOException {
File deleteOldFile = new File("E:\\Users\\PLACEHOLDER\\ExcelTestowy#2 — kopia.xlsx");
if (deleteOldFile.exists()) {
deleteOldFile.delete();
System.out.println("Deleted!");
}
File fT = new File("E:\\Users\\PLACEHOLDER\\ExcelTestowy#2.xlsx");
FileInputStream fTI = new FileInputStream(fT);
if (deleteOldFile.exists()) {
System.out.println("File exists!\n--------------");
} else {
System.out.println("File doesn't existst");
}
/////////////////////////////////
XSSFWorkbook wb = new XSSFWorkbook(fTI);
XSSFSheet sh = wb.getSheetAt(0);
XSSFTable tb = sh.getTables().get(0);
tb.setDisplayName("ExampleTableName"); //Works
tb.getColumns().get(0).setName("ExampleColumnName"); // Doesn't work
tb.createColumn("ExampleAdditionalColumnINeed"); //Doesn't work too.
File fTO = new File("E:\\Users\\PLACEHOLDER\\ExcelTestowy#2 — kopia.xlsx");
FileOutputStream fTOO = new FileOutputStream(fTO);
wb.write(fTOO);
fTOO.flush();
fTOO.close();
wb.close();
}
}
PS: I am beginner in Java - I had 3 years break in java. I apologise for my language.