excel样式格式问题
hei66 opened this issue · comments
hei commented
问题描述
读一个excel后,需要对这个excel中的某些数据(数据不固定,没办法用fill来处理)进行处理,回写到这个excel里面,希望回写的excel文件样式格式不发生改变,我应该怎么做
ljluestc commented
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelProcessor {
public static void main(String[] args) {
try {
FileInputStream inputStream = new FileInputStream("input.xlsx");
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
// Modify data in the Excel sheet
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
cell.setCellValue("New Value");
// Preserve style formatting
CellStyle style = cell.getCellStyle();
// Write the modified Excel data back to the file
FileOutputStream outputStream = new FileOutputStream("output.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
System.out.println("Excel file has been modified and saved successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}