如何使用JWord在.doc文件表格中添加Excel数据?
问题描述
我正在开发一款多文件转换APP,支持将Excel表格转换为PDF、.doc等格式。目前使用Apache POI读取Excel数据,借助JWord库生成Word文件,文件可成功创建,但无法像Excel那样按表格形式添加数据。JWord文档中有表格创建示例,但我不知道如何与Excel数据做映射,附上生成Word文件的代码,请求帮助。
现有代码
void generateWordFile() throws Exception{ try { File f = new File(Environment.getExternalStorageDirectory() + "/MultiFileCon"); if (!f.exists()) { f.mkdir(); Toast.makeText(this, "created dir", Toast.LENGTH_SHORT).show(); } SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); Date date = new Date(); // System.out.println(formatter.format(date)); Log.d("DATE", formatter.format(date) + ".pdf"); File docfile = new File(f.getAbsolutePath(), formatter.format(date) + ".doc"); FileInputStream input_document = new FileInputStream(new File(PathUtil.getPath(this, uriforExcel))); // Read workbook into HSSFWorkbook HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document); // Read worksheet into HSSFSheet HSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0); // To iterate over the rows Iterator<Row> rowIterator = my_worksheet.iterator(); //We will create output PDF document objects at this point Document iText_xls_2_pdf = new Document(); PdfWriter.getInstance(iText_xls_2_pdf, new FileOutputStream(docfile)); iText_xls_2_pdf.open(); //we have two columns in the Excel sheet, so we create a PDF table with two columns //Note: There are ways to make this dynamic in nature, if you want to. PdfPTable my_table = new PdfPTable(7); //We will use the object below to dynamically add new data to the table PdfPCell table_cell; while(rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while(cellIterator.hasNext()) { Cell cell = cellIterator.next(); //Fetch CELL switch(cell.getCellType()) { //Identify CELL type //you need to add more code here based on //your requirement / transformations case Cell.CELL_TYPE_STRING: //Push the data from Excel to PDF Cell table_cell=new PdfPCell(new Phrase(cell.getStringCellValue())); Log.d("DOL", cell.getStringCellValue()); datatobe.append(cell.getStringCellValue()+"\n"); //feel free to move the code below to suit to your needs my_table.addCell(table_cell); break; } //next line } // Log.d("DOL", "Convert_to_PDF: "+datatobe); } //Finally add the table to PDF document iText_xls_2_pdf.add(my_table); iText_xls_2_pdf.close(); //we created our pdf file.. input_document.close(); WordDocument doc = new WordDocument(); Run run = new Run(); run.addText(datatobe.toString()); Paragraph paragraph = new Paragraph(); paragraph.add(run); doc.getBody().add(paragraph); doc.save(docfile.getAbsolutePath(), true); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } }
解决方案
你当前代码只是把Excel数据按纯文本换行添加到Word段落,没有构建表格结构。要实现Excel到Word表格的映射,需在遍历Excel行和单元格时同步创建JWord的表格组件,具体步骤如下:
- 初始化Word表格:先获取Excel工作表的列数,以此创建对应列数的Word表格,保证和Excel列数匹配。
- 逐行同步创建表格行:每遍历一行Excel数据,就创建一个Word表格行。
- 逐单元格填充内容:将每个Excel单元格的内容对应填充到Word表格的单元格中,同时处理不同单元格类型(如数字、日期等)。
修改后的核心代码替换原来的Word生成部分即可:
// 重新打开Excel输入流(之前生成PDF时已关闭) input_document = new FileInputStream(new File(PathUtil.getPath(this, uriforExcel))); my_xls_workbook = new HSSFWorkbook(input_document); my_worksheet = my_xls_workbook.getSheetAt(0); rowIterator = my_worksheet.iterator(); WordDocument doc = new WordDocument(); // 动态获取Excel列数,适配不同表格结构 int columnCount = 0; if (my_worksheet.getRow(0) != null) { columnCount = my_worksheet.getRow(0).getLastCellNum(); } else { columnCount = my_worksheet.getLastCellNum(); } // 创建对应列数的Word表格 Table table = new Table(doc, columnCount); doc.getBody().add(table); while(rowIterator.hasNext()) { Row excelRow = rowIterator.next(); Iterator<Cell> cellIterator = excelRow.cellIterator(); // 创建Word表格行 TableRow wordRow = new TableRow(table); table.addRow(wordRow); while(cellIterator.hasNext()) { Cell excelCell = cellIterator.next(); String cellValue = ""; // 处理Excel中不同类型的单元格 switch(excelCell.getCellType()) { case Cell.CELL_TYPE_STRING: cellValue = excelCell.getStringCellValue(); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(excelCell)) { cellValue = formatter.format(excelCell.getDateCellValue()); } else { cellValue = String.valueOf(excelCell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BOOLEAN: cellValue = String.valueOf(excelCell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: cellValue = excelCell.getCellFormula(); break; default: cellValue = ""; } // 创建Word表格单元格并填充内容 TableCell wordCell = new TableCell(wordRow); wordRow.addCell(wordCell); Run run = new Run(); run.addText(cellValue); Paragraph para = new Paragraph(); para.add(run); wordCell.add(para); } } // 保存Word文件 doc.save(docfile.getAbsolutePath(), true); input_document.close();
关键说明
- 重新打开输入流:因为生成PDF时已关闭输入流,需重新读取Excel数据用于生成Word表格。
- 动态列数:避免硬编码列数,适配不同结构的Excel表格。
- 多类型处理:补充了数字、日期、布尔值等单元格类型的处理,确保Excel数据完整映射到Word表格。
内容的提问来源于stack exchange,提问作者vikram Choudhary
相关产品推荐
相关产品推荐

