我已经设置了一个 api,它在给定的路径中发送文件的数据。我正在尝试从 api 获取 .xlsx 文件并将其传递给XSSFWorkbook
进一步处理。为此,我尝试了两种方式:
- 将内容传递给 InputStream,然后将其传递给 XSSFWorkbook。这是一个错误
invalid code lengths set
val excelData = getFileContent(remoteFsUrl, filePath, apiKey).right.get
val excelFile = IOUtils.toInputStream(excelData, "UTF-8")
val reader = new XSSFWorkbook(OPCPackage.open(excelFile)) <-- error here
reader.getSheetAt(0)
- 将文件保存在某个本地路径中并读取它。但它正在破坏 xlsx 文件,就好像我试图将响应保存为 Postman 中的文件一样。
val excelData = getFileContent(remoteFsUrl, filePath, apiKey).right.get
new PrintWriter("filename") { write(excelData); close }
val excelFile = new FileInputStream(new File(filePath))
val reader = new XSSFWorkbook(excelFile)
reader.getSheetAt(0)
我可以知道上述方法是否有任何问题或有更好的方法吗?
PS:我提到的API是建立在fastapi之上的。
编辑:实施getFileContent
def getFileContent(url: String, path: String, apiKey: String, timeOut: Int = 300) = {
val request = basicRequest
.get(uri"$url/fetchfile?file_path=$path&access_token=$apiKey")
implicit val backend: SttpBackend[Identity, Nothing, NothingT]
= HttpURLConnectionBackend(options = SttpBackendOptions.connectionTimeout(timeOut.seconds))
val response = request.readTimeout(timeOut.seconds).send()
val someFile = new File("path/t.xlsx")
val data = response.body.right.get.getBytes
val bos = new BufferedOutputStream(new FileOutputStream(someFile))
bos.write(data)
bos.close()
println(response)
response.body
}