【问题标题】:Apache POI Excel copy from TXT来自 TXT 的 Apache POI Excel 副本
【发布时间】:2014-06-16 14:42:08
【问题描述】:

我遇到了问题,我想寻求您的帮助。问题是,我正在尝试使用 Apache POI 将文本文件 (.txt) 中的数据放入 Excel 工作表中。我从 txt 复制所有数据没有问题,但是当我粘贴到选定的工作表单元格时,它带有我选择的单元格内的所有值(当然,这是我命令做的)。

当我手动操作时,打开 txt 文件,创建新的 excel 文件,ctrl+c txt 文件,ctrl+v 在 excel 工作表上,所有选项卡就位,就像我希望的那样。 txt 文件是标签式的,因此 excel 了解它需要位于其他列上。 我对它的编码完全没有问题,因为没有错误或其他什么,我可以通过 3 种不同的方式手动完成。

我用来从 txt 复制的代码。

String all= "";
try (BufferedReader br = new BufferedReader(new FileReader("C:\\arquivo.txt"))) {
     String sCurrentLine;
     while ((sCurrentLine = br.readLine()) != null) {
        all = all + "\n" + sCurrentLine;
    }
    } catch (IOException e) {
        e.printStackTrace();
}

用于将值设置为 excel 的代码。

String fileName = "C:/Testing.xls";
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Teste");
HSSFRow row = sheet.createRow((short) 0);
row.createCell(0).setAsActiveCell();
FileOutputStream fileOut = new FileOutputStream(fileName);
workbook.write(fileOut);
fileOut.close();

我想知道的是:有什么方法可以做到吗?

【问题讨论】:

    标签: java excel apache apache-poi


    【解决方案1】:

    您需要解析输入文本,然后根据该文本包含的内容创建行和单元格。
    试试这样的:

        LinkedList<String[]> text_lines = new LinkedList<>();
        try (BufferedReader br = new BufferedReader(new FileReader("C:\\arquivo.txt"))) {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                text_lines.add(sCurrentLine.split("\\t"));                 
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        String fileName = "C:/Testing.xls";
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("Teste");
        int row_num = 0;
        for(String[] line : text_lines){
            Row row = sheet.createRow(row_num++);
            int cell_num = 0;
            for(String value : line){
                Cell cell = row.createCell(cell_num++);
                cell.setCellValue(value);
            }
        }
    
        FileOutputStream fileOut = new FileOutputStream(fileName);
        workbook.write(fileOut);
        fileOut.close();
    

    这会将文本文件的每一行读入由制表符分隔的String[] 数组(这是 Excel 中的默认分隔符),并放入有序列表中。您可以将split 函数中的正则表达式模式更改为适合您的文本的任何内容。第二部分遍历字符串数组列表并将每个列表写入一行,将列表的每个块(单词、句子、数字...)写入自己的单元格。

    【讨论】:

    • 你是如何在代码中写入文件Testing.xls的?
    • @whatthefish:提问者代码中的文件写入部分看起来不错,我将其添加到响应中。
    【解决方案2】:

    使用选项卡式 delemeter "\t" 从文本文件中拆分每一行并写入适当的单元格值。 分享你的代码,让你得到更多帮助。

    【讨论】:

    • 我不想删除 txt 文件,因为有时该 txt 会非常大,所以我试图避免这种情况以防止一些性能损失
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    相关资源
    最近更新 更多