源代码:
@Test
void testPwd() {
// 加载文件流
try (FileInputStream fileInputStream = new FileInputStream("D:\\work\\test\\file-parse\\excel\\testPwd.xlsx");) {
//boolean passWordProtected = Document.isPassWordProtected(inputStream);
Locale.setDefault(Locale.ROOT);
Workbook workbook = new Workbook();
workbook.setOpenPassword("1010");
workbook.loadFromStream(fileInputStream);
// 获取工作表,sheet1、sheet2...
WorksheetsCollection worksheets = workbook.getWorksheets();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < worksheets.size(); i++) {
Worksheet worksheet = worksheets.get(i);
String name = worksheet.getName();
// 间隔开工作表表名
sb.append(name).append(",");
for (int rowNum = worksheet.getFirstRow(); rowNum <= worksheet.getLastRow(); rowNum++) {
for (int columnNum = worksheet.getFirstColumn(); columnNum <= worksheet.getLastColumn(); columnNum++) {
String text = worksheet.getText(rowNum, columnNum);
if (StrUtil.isNotBlank(text)) {
sb.append(text.trim());
}
}
}
System.out.println(sb);
}
} catch (IOException e) {
e.fillInStackTrace();
}
}
设置了正确的密码报空指针,通过设置错误的密码可以确定文件流是加载到了的。
错误密码报错:
class com.spire.office.packages.sprihg: Invalid password.
运行环境:windows11、IntelliJ IDEA 2023.2、org.junit.jupiter.api.Test、spire.office.free(5.3.1)