我看着this post 我知道这篇文章很旧,我在excel文件中也遇到了同样的问题。我的情况是:我有一个用javaFX编写的桌面应用程序,用户将TableView内容导出到excel文件中。一切正常,除非文件试图打开时消息被用户锁定以进行编辑。 如何强制或解决从生成文件的应用程序解锁文件的问题? 这是我的初始代码
String directory = CreateDir();
if (rs != null) {
File file_excel = new File(directory + "\\" + reportName + ".xls");
file_excel.createNewFile();
while (rs.next()) {
pc.exportToXls_File(sql, uID, uPW, file_excel);
}
Desktop.getDesktop().open(file_excel);
}
exportToXls_File函数
public void exportToXls_File(String sql, String userName, String passWord, File fileName)
throws SQLException, FileNotFoundException, IOException, Exception {
ActionEvent event = new ActionEvent();
DBConnection dbc = new DBConnection();
conn = dbc.getConnection(event, userName, passWord);
try {
try (
/**
* Create new Excel workbook and sheet
*/
HSSFWorkbook xlsWorkbook = new HSSFWorkbook()) {
HSSFSheet xlsSheet = xlsWorkbook.createSheet();
short rowIndex = 0;
/**
* Execute SQL query
*/
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
/**
* Get the list of column names and store them as the first Row
* of the spreadsheet.
*/
ResultSetMetaData colInfo = rs.getMetaData();
List<String> colNames = new ArrayList<>();
HSSFRow titleRow = xlsSheet.createRow(rowIndex++);
for (int i = 1; i <= colInfo.getColumnCount(); i++) {
colNames.add(colInfo.getColumnName(i));
titleRow.createCell((int) (i - 1)).setCellValue(
new HSSFRichTextString(colInfo.getColumnName(i)));
xlsSheet.setColumnWidth((int) (i - 1), (short) 4000);
}
/**
* Save all the data from the database table rows
*/
while (rs.next()) {
HSSFRow dataRow = xlsSheet.createRow(rowIndex++);
int colIndex = 0;
for (String colName : colNames) {
dataRow.createCell(colIndex++).setCellValue(
new HSSFRichTextString(rs.getString(colName)));
}
}
/**
* Write to disk
*/
xlsWorkbook.write(new FileOutputStream(fileName));
xlsWorkbook.close();
}
} catch (IOException | SQLException ex) {
out.println(ex);
} finally {
if (conn != null) {
stmt.close();
closeConnection((OracleConnection) conn);
conn.close();
}
}
}
谢谢