一、导入依赖
<!--读写Excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
二、代码
public static void setExcelScale(String inputPath, String outPath) throws Exception {
XSSFWorkbook workbook;
try {
workbook = new XSSFWorkbook(new FileInputStream(inputPath));
} catch (FileNotFoundException e) {
LOG.error("setExcelScale fail: 源文件不存在", e);
throw new Exception("setExcelScale fail: 源文件不存在");
} catch (IOException e) {
LOG.error("setExcelScale fail: 读取源文件IO异常", e);
throw new Exception("setExcelScale fail: 读取源文件IO异常");
}
OutputStream fos = null;
try {
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
XSSFSheet sheet = workbook.getSheetAt(i);
XSSFPrintSetup print = sheet.getPrintSetup();
print.setLandscape(true);
print.setFitHeight((short)0);
print.setFitWidth((short)1);
print.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
sheet.setFitToPage(true);
}
File file = new File(outPath);
fos = new FileOutputStream(file);
workbook.write(fos);
} catch (Exception e) {
LOG.error("setExcelScale fail: 创建输出文件IO异常", e);
throw new Exception("setExcelScale fail: 创建输出文件IO异常");
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}