我有一个Spring动作,应该在Excel文件中读取并访问单元格中包含的值。我正在使用Java Excel API来处理Excel文件。我希望它从外部文件夹而不是从我的项目的根目录中读取。我遇到的问题是Spring MVC无法识别我的文件。我几乎每次都会收到此错误:
文件名,目录名或卷标语法不正确
我甚至尝试了类似的事情:
Resource banner = resourceLoader.getResource("http://howtodoinjava.com/readme.txt");
as seen here,但仍然没有运气。我的控制器代码:
@RequestMapping(value="migrateexcel", method = RequestMethod.POST)
public String migrateexcel(Model uiModel, HttpServletRequest httpServletRequest) throws BiffException, IOException {
String fileName = httpServletRequest.getParameter("filename");
if (! fileName.isEmpty() && fileName!= null) {//just doing this as the logic kicks in from a form
FileSystemResource resource = new FileSystemResource("file:C:/Users/Administrator/Desktop/myfolder/test.xlsx");
File xlsFile = resource.getFile();
String temp = "";
Workbook workbook = Workbook.getWorkbook(xlsFile);
Sheet sheet = workbook.getSheet(0);
for(int i =0; i<sheet.getRows(); i++){
for(int j =0; j < sheet.getColumns(); j++){
Cell cell = sheet.getCell(j,i);
temp = cell.getContents();
System.out.println(temp);
}
}
uiModel.addAttribute("message", "Excel Data migrated successfully");
return "rates/processexcel";
}else{
uiModel.addAttribute("message", "Please select a file before submiting");
return "rates/processexcel";
}
}
答案 0 :(得分:1)
我测试了它,似乎唯一的问题是你引用文件的方式。
这两种方式应该有效(除非存在某种许可问题):
"C:/Users/Administrator/Desktop/myfolder/test.xlsx"
或
"C:\\Users\\Administrator\\Desktop\\myfolder\\test.xlsx"
Spring和Spring MVC实际上与这个问题无关,但是FileSystemResource
的构造函数在String或java.io.File
中期望相同的语法。