将 Excel/CSV 文件中的数据转换为字符串。

huangapple go评论95阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月4日 16:24:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63242903.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定