JAVA使用POI读写word 乱码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA使用POI读写word 乱码相关的知识,希望对你有一定的参考价值。

在使用POI写word的时候不对字节编码成uft-8生成的word就会乱码。编码后读取是就会报:不能打开一个加密的文件。。。。求大神给段读写word的方法。

参考技术A

public static void main(String args[])
throws Exception

XWPFDocument doc = new XWPFDocument();
XWPFParagraph p1 = doc.createParagraph();
p1.setAlignment(ParagraphAlignment.CENTER);
p1.setBorderBottom(Borders.DOUBLE);
p1.setBorderTop(Borders.DOUBLE);
p1.setBorderRight(Borders.DOUBLE);
p1.setBorderLeft(Borders.DOUBLE);
p1.setBorderBetween(Borders.SINGLE);
p1.setVerticalAlignment(TextAlignment.TOP);
XWPFRun r1 = p1.createRun();
r1.setBold(true);
r1.setText("The quick brown fox");
r1.setBold(true);
r1.setFontFamily("Courier");
r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
r1.setTextPosition(100);
XWPFParagraph p2 = doc.createParagraph();
p2.setAlignment(ParagraphAlignment.RIGHT);
p2.setBorderBottom(Borders.DOUBLE);
p2.setBorderTop(Borders.DOUBLE);
p2.setBorderRight(Borders.DOUBLE);
p2.setBorderLeft(Borders.DOUBLE);
p2.setBorderBetween(Borders.SINGLE);
XWPFRun r2 = p2.createRun();
r2.setText("jumped over the lazy dog");
r2.setStrike(true);
r2.setFontSize(20);
XWPFRun r3 = p2.createRun();
r3.setText("and went away");
r3.setStrike(true);
r3.setFontSize(20);
r3.setSubscript(VerticalAlign.SUPERSCRIPT);
XWPFParagraph p3 = doc.createParagraph();
p3.setWordWrap(true);
p3.setPageBreak(true);
p3.setAlignment(ParagraphAlignment.BOTH);
p3.setSpacingLineRule(LineSpacingRule.EXACT);
p3.setIndentationFirstLine(600);
XWPFRun r4 = p3.createRun();
r4.setTextPosition(20);
r4.setText("To be, or not to be: that is the question: Whether 'tis nobler in the mind to suffer The slings and arrows of outrageous fortune, Or to take arms against a sea of troubles, And by opposing end them? To die: to sleep; ");
r4.addBreak(BreakType.PAGE);
r4.setText("No more; and by a sleep to say we end The heart-ache and the thousand natural shocks That flesh is heir to, 'tis a consummation Devoutly to be wish'd. To die, to sleep; To sleep: perchance to dream: ay, there's the rub; .......");
r4.setItalic(true);
XWPFRun r5 = p3.createRun();
r5.setTextPosition(-10);
r5.setText("For in that sleep of death what dreams may come");
r5.addCarriageReturn();
r5.setText("When we have shuffled off this mortal coil,Must give us pause: there's the respectThat makes calamity of so long life;");
r5.addBreak();
r5.setText("For who would bear the whips and scorns of time,The oppressor's wrong, the proud man's contumely,");
r5.addBreak(BreakClear.ALL);
r5.setText("The pangs of despised love, the law's delay,The insolence of office and the spurns.......");
FileOutputStream out = new FileOutputStream("simple.docx");
doc.write(out);
out.close();
本回答被提问者和网友采纳

使用poi读写Excel

       对于一个程序猿来说,文件操作是常常遇到的,尤其是对Excel文件的操作。


       在这里介绍一下我在项目中用到的一个操作Excel的工具——POI。关于POI的一些概念。网络上非常多,具体信息大家能够自行百度。我在这里仅仅做简介。

POI是apache的类库,主要是为java开发者提供对Office文件(word、ppt、Excel)处理的支持。我这里主要给出几个样例来说明演示一下。


       准备工作

       我用的版本号是3.10.1,须要的jar有:

  • dom4j.jar
  • log4j-1.2.13.jar
  • poi-3.10.1-20140818.jar
  • poi-ooxml-3.10.1-20140818.jar
  • poi-ooxml-schemas-3.10.1-20140818.jar
  • poi-scratchpad-3.10.1-20140818.jar
       代码演示样例1.读取Excel
public void testReadExcel() {
  try {
    // 读取Excel
    Workbook wb = new HSSFWorkbook(new FileInputStream("d:\\2.xls"));

    // 获取sheet数目
    for (int t = 0; t < wb.getNumberOfSheets(); t++) {
      Sheet sheet = wb.getSheetAt(t);
      Row row = null;
      int lastRowNum = sheet.getLastRowNum();

      // 循环读取
      for (int i = 0; i <= lastRowNum; i++) {
        row = sheet.getRow(i);
        if (row != null) {
          // 获取每一列的值
          for (int j = 0; j < row.getLastCellNum(); j++) {
            Cell cell = row.getCell(j);
            String value = getCellValue(cell) ;
            if(!value.equals("")){
              System.out.print(value + " | ");
            }
          }
          System.out.println();
        }
      }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}
      用到了一个方法:
/***
 * 读取单元格的值
 * 
 * @Title: getCellValue
 * @Date : 2014-9-11 上午10:52:07
 * @param cell
 * @return
 */
private String getCellValue(Cell cell) {
  Object result = "";
  if (cell != null) {
    switch (cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:
      result = cell.getStringCellValue();
      break;
    case Cell.CELL_TYPE_NUMERIC:
      result = cell.getNumericCellValue();
      break;
    case Cell.CELL_TYPE_BOOLEAN:
      result = cell.getBooleanCellValue();
      break;
    case Cell.CELL_TYPE_FORMULA:
      result = cell.getCellFormula();
      break;
    case Cell.CELL_TYPE_ERROR:
      result = cell.getErrorCellValue();
      break;
    case Cell.CELL_TYPE_BLANK:
      break;
    default:
      break;
    }
  }
  return result.toString();
}
       解释一下,首先将文件读入到工作簿Workbook中,Workbook是一个接口,他有2个实现:HSSFWorkbook和XSSFWorkbook。前者是用来读取97-03版的Excel,扩展名为xls。后者是读取07及以后的版本号。扩展名为xlsx。

读入到workbook中,然后循环全部的sheet。在sheet循环全部的有效行和有效列。当中sheet.getLastRowNum()获得最后一行的索引值(从0開始),而sheet.getPhysicalNumberOfRows()则是获取的最后一行的行号(从1開始)。这里要注意的是循环列不是在sheet中循环。而是在row中循环。


       效果图例如以下:
技术分享技术分享
技术分享

       代码演示样例2. 写入Excel文件
public void testWriteExcel() {
  String excelPath = "d:/3.xls";

  Workbook workbook = null;
  try {
    // XSSFWorkbook used for .xslx (>= 2007), HSSWorkbook for 03 .xsl
    workbook = new HSSFWorkbook();// XSSFWorkbook();//WorkbookFactory.create(inputStream);
  } catch (Exception e) {
    System.out.println("创建Excel失败: ");
    e.printStackTrace();
  }
  if (workbook != null) {
    Sheet sheet = workbook.createSheet("測试数据");
    Row row0 = sheet.createRow(0);
    for (int i = 0; i < 6; i++) {
      Cell cell = row0.createCell(i, Cell.CELL_TYPE_STRING);
      cell.setCellValue("列标题" + i );
      //sheet.autoSizeColumn(i);//自己主动调整宽度
    }
    for (int rowNum = 1; rowNum < 10; rowNum++) {
      Row row = sheet.createRow(rowNum);
      for (int i = 0; i < 6; i++) {
        Cell cell = row.createCell(i, Cell.CELL_TYPE_STRING);
        cell.setCellValue("单元格" + String.valueOf(rowNum + 1)
            + String.valueOf(i + 1));
      }
    }
    try {
      FileOutputStream outputStream = new FileOutputStream(excelPath);
      workbook.write(outputStream);
      outputStream.flush();
      outputStream.close();
    } catch (Exception e) {
      System.out .println("写入Excel失败: ");
      e.printStackTrace();
    }
  }
}
       效果图例如以下:
技术分享

       怎么样,非常easy吧。仅仅要你使用了poi,无论你有没有安装Office,都能够完美的操作Office文件。小伙伴们。都快来试试看吧。













以上是关于JAVA使用POI读写word 乱码的主要内容,如果未能解决你的问题,请参考以下文章

使用poi读写Excel

java读写word文档,完美解决方案

[原创]java读写word文档,完美解决方案

NPOI 表头页眉页脚重复设置

POI 详细介绍

Java读取word文件内容