英文:
Convert excel/csv file data in string
问题
如何读取Excel/CSV工作簿对象中的数据并保存为字符串。
String fileData;
Workbook workbook = new XSSFWorkbook();
workbook.write(fileData);
System.out.println(fileData);
我不想在我的程序中使用文件服务器依赖项。
所以有没有办法直接将内容写入字符串变量中。
英文:
How to read the excel/csv work book object data in string.
String fileData;
Workbook workbook = new XSSFWorkbook();
workbook.write(fileData);
System.out.println(fileData);
I dont want to use file serer dependency in my progarm..
So is there any way I can directly write the contents to string variable..
答案1
得分: 0
如果您正在使用org.apache.poi,那么您可以像这样将Workbook
写入String
:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
workbook.close();
String output = new String(baos.toByteArray(), Charset.defaultCharset());
但是字符串output
将包含随机字符,因为Workbook写入的是一个二进制文件,而不是普通文本。
因此,更好的方法是逐行读取Workbook
并将内容保存在StringBuilder
中,例如:
StringBuilder sb = new StringBuilder();
for(Row r : workbook.getSheet("MySheet")){
for (Cell c : r) {
// 假设单元格的类型为String
sb.append(c.getStringCellValue()+" ");
}
sb.append("\n");
}
String result = sb.toString();
字符串result
将包含Workbook
的内容。
英文:
If you are using org.apache.poi then you can write the Workbook
into a String
like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
workbook.close();
String output = new String(baos.toByteArray(), Charset.defaultCharset());
However the string output
will contain random characters, because the Workbook writes a binary file which is not normal text.
So a better approach is to read the Workbook
row by row and save the content in a StringBuilder
, for example:
StringBuilder sb = new StringBuilder();
for(Row r : workbook.getSheet("MySheet")){
for (Cell c : r) {
// Assuming the type of the cell is String
sb.append(c.getStringCellValue()+" ");
}
sb.append("\n");
}
String result = sb.toString();
The string result
will contain the content of the Workbook
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论