进行office转pdf时遇到excel转pdf会出现列数太多导致折行问题
解决此问题,可以先将excel进行打印设置,再把设置好的文档拿去转pdf
/**
* excel设置 打印缩放比例
*
* @param inputPath
* @param outPath
*/
public static void setExcelScale(String inputPath, String outPath) {
//读取excel文件
XSSFWorkbook workbook;
try {
workbook = new XSSFWorkbook(new FileInputStream(inputPath));
} catch (FileNotFoundException e) {
log.error("setExcelScale fail: 源文件不存在", e);
throw new MyException(ResultCode.FAILURE, "setExcelScale fail: 源文件不存在");
} catch (IOException e) {
log.error("setExcelScale fail: 读取源文件IO异常", e);
throw new MyException(ResultCode.FAILURE, "setExcelScale fail: 读取源文件IO异常");
}
OutputStream fos = null;
try {
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {//获取每个Sheet表
XSSFSheet sheet = workbook.getSheetAt(i);
//打印设置
XSSFPrintSetup print = sheet.getPrintSetup();
print.setLandscape(true); // 打印方向,true:横向,false:纵向(默认)
print.setFitHeight((short)0);//设置高度为自动分页
print.setFitWidth((short)1);//设置宽度为一页
print.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE); //纸张类型
// print.setScale((short)55);//自定义缩放①,此处100为无缩放
//启用“适合页面”打印选项的标志
sheet.setFitToPage(true);
}
// Excel文件生成后存储的位置。
File file = new File(outPath);
fos = new FileOutputStream(file);
workbook.write(fos);
} catch (Exception e) {
log.error("setExcelScale fail: 创建输出文件IO异常", e);
throw new MyException(ResultCode.FAILURE, "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();
}
}
}
}
public static void main(String[] args) {
setExcelScale("d:/tmp/源文件.xlsx", "d:/tmp/设置后的文件.xlsx");
}
其他打印Page选项设置:
更多操作请跳转:POI操作Excel常用方法
7.设置打印
HSSFPrintSetup print = (HSSFPrintSetup) sheet.getPrintSetup();
print.setLandscape(true);//设置横向打印
print.setScale((short) 70);//设置打印缩放70%
print.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);//设置为A4纸张
print.setLeftToRight(true);//設置打印顺序先行后列,默认为先列行
print.setFitHeight((short) 10);设置缩放调整为10页高
print.setFitWidth((short) 10);设置缩放调整为宽高