[英]I can't print the info in doc file in a sequence when I read the inf from the Excel sheet
輸出格式應在文檔中如下所示:
這是excel工作表的輸入格式:
我正在嘗試閱讀Excel工作表,並試圖以系統的順序在Word文檔中打印信息。 我可以從Excel工作表中讀取,但無法在doc文件中打印。 我該怎么辦?
它顯示的是Excel文件的最后一行,即僅覆蓋doc文件而不附加文件。 有沒有辦法添加這個文件?
public static void main(String[] args) throws Exception {
File src = new File("convertion java.xls");
FileInputStream fis = new FileInputStream(src);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet1 = wb.getSheetAt(0);
String[] header = new String[4];
for (int k = 0; k < 4; k++) {
header[k] = sheet1.getRow(0).getCell(k).getStringCellValue();
}
FileOutputStream out = new FileOutputStream(new File("output.docx"));
for (int j = 1; j < 5; j++) {
for (int i = 0; i < 4; i++) {
result = sheet1.getRow(j).getCell(i).getStringCellValue();
doc = header[i] + " = " + result;
System.out.println(doc);
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun paragraphOneRunOne = paragraph.createRun();
paragraphOneRunOne.setText(doc);
document.write(out);
}
System.out.println();
}
wb.close();
out.close();
}}
我希望輸出會附加doc文件,但不會覆蓋它。
您為在Excel
表中找到的每個單元格創建一個新的XWPFDocument
。 那不會導致您想要的結果。 為了獲得所需的結果,只需要一個 XWPFDocument
,然后根據找到的Excel
單元格的內容用段落填充。
對於Excel
部分,您應該使用org.apache.poi.ss.usermodel.*
而不是HSSF
因為這更通用,並且還可以讀取XSSF
( *.xlsx
)。
並且您不應該依賴getStringCellValue
因為並非所有Excel
單元格內容都必須始終為文本。 相反,您應該使用DataFormatter
從Excel
單元格中獲取單元格內容。
完整的例子:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xwpf.usermodel.*;
class ReadExcelWriteWord {
public static void main(String[] args) throws Exception {
DataFormatter formatter = new DataFormatter();
Workbook workbook = WorkbookFactory.create(new FileInputStream("convertion java.xls"));
FileOutputStream out = new FileOutputStream("output.docx");
XWPFDocument document = new XWPFDocument();
Sheet sheet = workbook.getSheetAt(0);
Row row = null;
Cell cell = null;
XWPFParagraph paragraph = null;
XWPFRun run = null;
String[] header = new String[4];
row = sheet.getRow(0);
if (row != null) {
for (int k = 0; k < 4; k++) {
cell = row.getCell(k);
header[k] = formatter.formatCellValue(cell);
}
}
String result = "";
String doc = "";
for (int j = 1; j < 5; j++) {
row = sheet.getRow(j);
if (row != null) {
for (int i = 0; i < 4; i++) {
cell = row.getCell(i);
result = formatter.formatCellValue(cell);
doc = header[i] + " = " + result;
System.out.println(doc);
paragraph = document.createParagraph();
run = paragraph.createRun();
run.setText(doc);
}
}
paragraph = document.createParagraph();
System.out.println();
}
workbook.close();
document.write(out);
out.close();
document.close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.