我需要使用密码或加密的xls文件DOWNLOAD。
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import com.emmanuelrosa.frostedsheets.*
def downloadxls(){
/*
* Creates a workbook with Apache POI and decorates it
* with Frosted Sheets.
*/
response.setContentType('application/vnd.ms-excel')
response.setHeader('Content-Disposition', 'Attachment;Filename="data.xls"')
// response.setContentType("APPLICATION/OCTET-STREAM")
// response.setHeader('Content-Disposition', 'Attachment;Filename="archivo.buf"')
def outputStream = response.getOutputStream()
def workbook = new FrostedWorkbook(new HSSFWorkbook())
workbook['Students'].with {
append(['First Name', 'Last Name', 'Age'])
append(['John', 'Doe', '20'])
append(['Jane', 'Smith', '18'])
}
workbook['Courses'].with {
append(['Course Name', 'Number of Units'])
append(['Algebra', 3])
append(['English Grammar', 5])
}
/*
* workbook is an instance of FrostedWorkbook,
* which implements the Workbook interface.
* The writeProtectWorkbook() method is provided
* by HSSFWorkbook (it's not in the interface).
* FrostedWorkbook.workbook is the decorated HSSFWorkbook
*/
workbook.workbook.writeProtectWorkbook('password', 'user')
workbook.write(response.outputStream)
outputStream << workbook
outputStream.flush()
文件下载代码。使用这段代码,我可以下载.xls文件,但即使添加了所有数据,仍然没有加密。
outputStream.close()
}
问题是您下载的文件未加密。
答案 0 :(得分:2)
您正在尝试使用两个库来创建Excel工作簿:JXL和Apache POI。他们彼此不知道任何。所以JXL忽略了密码。
加密和密码保护之间存在差异。两者都使用密码,但密码保护 不加密文件。该文件仍可以读取,但不能修改。
这是一个显示如何对工作簿进行密码保护的示例。我正在使用我的库Frosted Sheets,这是Apache POI的便利包装。
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import com.emmanuelrosa.frostedsheets.*
/*
* Creates a workbook with Apache POI and decorates it
* with Frosted Sheets.
*/
def workbook = new FrostedWorkbook(new HSSFWorkbook())
workbook['Students'] << [
['First Name', 'Last Name', 'Age'],
['John', 'Doe', '20'],
['Jane', 'Smith', '18']
]
workbook['Courses'] << [
['Course Name', 'Number of Units'],
['Algebra', 3],
['English Grammar', 5]
]
/*
* workbook is an instance of FrostedWorkbook,
* which implements the Workbook interface.
* The writeProtectWorkbook() method is provided
* by HSSFWorkbook (it's not in the interface).
* FrostedWorkbook.workbook is the decorated HSSFWorkbook
*/
workbook.workbook.writeProtectWorkbook('password', 'user')
workbook.write(response.outputStream)
FrostedSheets 现在为XLSX工作簿提供加密。您只需要使用0.3.0或更高版本:
import com.emmanuelrosa.frostedsheets.*
/*
* Creates an XLSX workbook with Apache POI and decorates it
* with Frosted Sheets.
*/
def workbook = FrostedWorkbook.createXLSX()
workbook['Students'] << [
['First Name', 'Last Name', 'Age'],
['John', 'Doe', '20'],
['Jane', 'Smith', '18'],
]
workbook['Courses'] << [
['Course Name', 'Number of Units'],
['Algebra', 3],
['English Grammar', 5]
]
workbook.writeEncrypted(outputStream: response.outputStream, password: 'password')
警告:在加密过程中,工作簿未加密写入临时存储。默认值是字节数组(RAM),但也可以使用临时文件。
此外,请确保将响应标头中的文件扩展名更改为 xlsx 。