使用Java从Excel读取数据并写入Docx文件

时间:2018-10-24 09:23:21

标签: java apache-poi docx4j

我在Excel工作表中有一些带有标头的记录。我想读取所有记录并使用java.header一起写到docx文件。谢谢您的帮助。 可以将一个excel写入其他excel文件,但无法在docx文件中写入。 我已经尝试过这种方法,但是word文件生成为损坏。

<table>
    <tr>
        <th>Id</th>
        <th>Boat</th>
        <th>Engine</th>
        <th>Length</th>
        <th>Width</th> 
        <th>Owner</th>
    </tr>
    <?php foreach ($res as $row) { ?>
        <tr>
            <td><a href='https://link.to/somewhere?id=<?= $row["id"]; ?>'><?= $row["id"]; ?></a></td>
            <td><?= $row["boatType"]; ?></td>
            <td><?= $row["boatEngine"]; ?></td>
            <td><?= $row["boatLength"]; ?></td>
            <td><?= $row["boatWidth"]; ?></td>
            <td><?= $row["ownerName"]; ?></td>
        </tr>
    <?php } ?>

</table>

}

2 个答案:

答案 0 :(得分:0)

我建议使用Apache Poi lib(https://poi.apache.org/

答案 1 :(得分:0)

像这样重写代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ExcelReaderDemo {
    public static final String SAMPLE_XLSX_FILE_PATH = "C:/XLXSToDocx/Roaster.xlsm";
    public static final String FILE_PATH = "C:/XLXSToDocx/writeExcel.docx";

    public static void main(String[] args) throws IOException, InvalidFormatException {
        Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));

        System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");

        try {

            FileOutputStream fos = new FileOutputStream(FILE_PATH);

            workbook.write(fos);

            fos.close();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }
        System.out.println("DONE !!!");
    }
}