使用ApachePOI在java中编辑Microsoft office.doc文件

使用ApachePOI在java中编辑Microsoft office.doc文件,java,ms-word,apache-poi,.doc,hwpf,Java,Ms Word,Apache Poi,.doc,Hwpf,我正在编写java代码以实现以下目标 1.读取给定的Microsoft office文档(.doc)文件 2.在文件中搜索给定字符串 3.删除位于任何位置的给定字符串 4.在指定位置插入或替换任何给定字符串 5.将更新后的文件内容写入并保存到新的.doc文件中 我已经编写了一个代码来读取、搜索、插入或替换、删除和保存文件,它运行良好,但我无法保留输入文件中应用的文本格式(例如字体颜色、字体大小、对齐、左右缩进、样式等) 请任何人帮我解决这个问题 谢谢我建议您使用ApachePOI文档。 我将使用

我正在编写java代码以实现以下目标

1.读取给定的Microsoft office文档(.doc)文件

2.在文件中搜索给定字符串

3.删除位于任何位置的给定字符串

4.在指定位置插入或替换任何给定字符串

5.将更新后的文件内容写入并保存到新的.doc文件中

我已经编写了一个代码来读取、搜索、插入或替换、删除和保存文件,它运行良好,但我无法保留输入文件中应用的文本格式(例如字体颜色、字体大小、对齐、左右缩进、样式等)

请任何人帮我解决这个问题


谢谢

我建议您使用ApachePOI文档。 我将使用文档进行一些实验,并为Ms Excel工作表轻松地设置文本格式

我在浏览API时看到了DataFormat类及其层次结构, 内置信息类, 以及CellStyle类的setDataFormat方法。 所以做了一些实验,下面的代码似乎是有效的

XSSFCellStyle textFormatStyle = book.createCellStyle(); 
textFormatStyle.setDataFormat((short)BuiltinFormats.getBuiltinFormat("text")); 
XSSFCell cell = row.createCell(columnIndex++); 
cell.setCellStyle(textFormatStyle); 
现在,一旦创建了电子表格, 您可以编辑一个单元格,当您进行制表时, 格式仍为“文本”

我已经用完整的例子向你展示了另一种方法。。 在其中,我将显示一个效果,进一步你可以添加根据你的要求

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Style example");

HSSFFont font = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);

Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("This is bold");
cell.setCellStyle(style);


font = workbook.createFont();
font.setItalic(true);
style = workbook.createCellStyle();
style.setFont(font);

row = sheet.createRow(1);
cell = row.createCell(0);
cell.setCellValue("This is italic");
cell.setCellStyle(style);

try {
    FileOutputStream out = new FileOutputStream(new File("C:\\style.xls"));
    workbook.write(out);
    out.close();
    System.out.println("Excel written successfully..");

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
此代码将生成以下输出:


我建议您使用ApachePOI文档。 我将使用文档进行一些实验,并为Ms Excel工作表轻松地设置文本格式

我在浏览API时看到了DataFormat类及其层次结构, 内置信息类, 以及CellStyle类的setDataFormat方法。 所以做了一些实验,下面的代码似乎是有效的

XSSFCellStyle textFormatStyle = book.createCellStyle(); 
textFormatStyle.setDataFormat((short)BuiltinFormats.getBuiltinFormat("text")); 
XSSFCell cell = row.createCell(columnIndex++); 
cell.setCellStyle(textFormatStyle); 
现在,一旦创建了电子表格, 您可以编辑一个单元格,当您进行制表时, 格式仍为“文本”

我已经用完整的例子向你展示了另一种方法。。 在其中,我将显示一个效果,进一步你可以添加根据你的要求

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Style example");

HSSFFont font = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);

Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("This is bold");
cell.setCellStyle(style);


font = workbook.createFont();
font.setItalic(true);
style = workbook.createCellStyle();
style.setFont(font);

row = sheet.createRow(1);
cell = row.createCell(0);
cell.setCellValue("This is italic");
cell.setCellStyle(style);

try {
    FileOutputStream out = new FileOutputStream(new File("C:\\style.xls"));
    workbook.write(out);
    out.close();
    System.out.println("Excel written successfully..");

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
此代码将生成以下输出:


我将添加用于设置Ms Word文档样式的新解决方案。

public class CreateDocumentFromScratch {

    public static void main(String[] args) {
        XWPFDocument document = new XWPFDocument();

        XWPFParagraph paragraphOne = document.createParagraph();
        paragraphOne.setAlignment(ParagraphAlignment.CENTER);
        paragraphOne.setBorderBottom(Borders.SINGLE);
        paragraphOne.setBorderTop(Borders.SINGLE);
        paragraphOne.setBorderRight(Borders.SINGLE);
        paragraphOne.setBorderLeft(Borders.SINGLE);
        paragraphOne.setBorderBetween(Borders.SINGLE);

        XWPFRun paragraphOneRunOne = paragraphOne.createRun();
        paragraphOneRunOne.setBold(true);
        paragraphOneRunOne.setItalic(true);
        paragraphOneRunOne.setText("Hello world! This is paragraph one!");
        paragraphOneRunOne.addBreak();

        XWPFRun paragraphOneRunTwo = paragraphOne.createRun();
        paragraphOneRunTwo.setText("Run two!");
        paragraphOneRunTwo.setTextPosition(100);

        XWPFRun paragraphOneRunThree = paragraphOne.createRun();
        paragraphOneRunThree.setStrike(true);
        paragraphOneRunThree.setFontSize(20);
        paragraphOneRunThree.setSubscript(VerticalAlign.SUBSCRIPT);
        paragraphOneRunThree.setText(" More text in paragraph one...");

        XWPFParagraph paragraphTwo = document.createParagraph();
        paragraphTwo.setAlignment(ParagraphAlignment.DISTRIBUTE);
        paragraphTwo.setIndentationRight(200);
        XWPFRun paragraphTwoRunOne = paragraphTwo.createRun();
        paragraphTwoRunOne.setText("And this is paragraph two.");

        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(args[0]);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            document.write(outStream);
            outStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

我将添加用于设置Ms Word文档样式的新解决方案。

public class CreateDocumentFromScratch {

    public static void main(String[] args) {
        XWPFDocument document = new XWPFDocument();

        XWPFParagraph paragraphOne = document.createParagraph();
        paragraphOne.setAlignment(ParagraphAlignment.CENTER);
        paragraphOne.setBorderBottom(Borders.SINGLE);
        paragraphOne.setBorderTop(Borders.SINGLE);
        paragraphOne.setBorderRight(Borders.SINGLE);
        paragraphOne.setBorderLeft(Borders.SINGLE);
        paragraphOne.setBorderBetween(Borders.SINGLE);

        XWPFRun paragraphOneRunOne = paragraphOne.createRun();
        paragraphOneRunOne.setBold(true);
        paragraphOneRunOne.setItalic(true);
        paragraphOneRunOne.setText("Hello world! This is paragraph one!");
        paragraphOneRunOne.addBreak();

        XWPFRun paragraphOneRunTwo = paragraphOne.createRun();
        paragraphOneRunTwo.setText("Run two!");
        paragraphOneRunTwo.setTextPosition(100);

        XWPFRun paragraphOneRunThree = paragraphOne.createRun();
        paragraphOneRunThree.setStrike(true);
        paragraphOneRunThree.setFontSize(20);
        paragraphOneRunThree.setSubscript(VerticalAlign.SUBSCRIPT);
        paragraphOneRunThree.setText(" More text in paragraph one...");

        XWPFParagraph paragraphTwo = document.createParagraph();
        paragraphTwo.setAlignment(ParagraphAlignment.DISTRIBUTE);
        paragraphTwo.setIndentationRight(200);
        XWPFRun paragraphTwoRunOne = paragraphTwo.createRun();
        paragraphTwoRunOne.setText("And this is paragraph two.");

        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(args[0]);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            document.write(outStream);
            outStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

您可以使用以下代码:

public class EditingWord{

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String filename = "path to input file/file_input_name";
        List<String> paraList = new ArrayList<String>();
        try {

            XWPFDocument doc = new XWPFDocument(OPCPackage.open(new FileInputStream(filename)));
            List<XWPFParagraph> paragraphList = doc.getParagraphs();
            for (XWPFParagraph para : paragraphList) {
                if ((para.getStyle() != null) && (para.getNumFmt() != null)) {
                    for (XWPFRun run : para.getRuns()) {
                        String text = run.text();
                        text = text.replaceAll(text, "replacement" + text);
                        run.setText(text, 0);
                    }
                }
            }
            doc.write(new FileOutputStream("path to your file/output_File_name"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
公共类编辑字{
公共静态void main(字符串[]args){
//TODO自动生成的方法存根
String filename=“输入文件的路径/文件\输入\名称”;
List paraList=new ArrayList();
试一试{
XWPFDocument doc=newxwpfdocument(OPCPackage.open(newfileinputstream(filename));
List paragraphList=doc.getParagraphs();
用于(XWPF段落:段落列表){
if((para.getStyle()!=null)和&(para.getNumFmt()!=null)){
对于(XWPFRun:para.getRuns()){
String text=run.text();
text=text.replaceAll(text,“replacement”+text);
run.setText(文本,0);
}
}
}
doc.write(新文件输出流(“文件路径/输出文件名”);
}捕获(例外e){
e、 printStackTrace();
}
}
}

如果您想将内容保存到同一个文件中,可以更改
doc.write(新文件输出流(“输入文件/输入文件名的路径”)

您可以使用以下代码:

public class EditingWord{

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String filename = "path to input file/file_input_name";
        List<String> paraList = new ArrayList<String>();
        try {

            XWPFDocument doc = new XWPFDocument(OPCPackage.open(new FileInputStream(filename)));
            List<XWPFParagraph> paragraphList = doc.getParagraphs();
            for (XWPFParagraph para : paragraphList) {
                if ((para.getStyle() != null) && (para.getNumFmt() != null)) {
                    for (XWPFRun run : para.getRuns()) {
                        String text = run.text();
                        text = text.replaceAll(text, "replacement" + text);
                        run.setText(text, 0);
                    }
                }
            }
            doc.write(new FileOutputStream("path to your file/output_File_name"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
公共类编辑字{
公共静态void main(字符串[]args){
//TODO自动生成的方法存根
String filename=“输入文件的路径/文件\输入\名称”;
List paraList=new ArrayList();
试一试{
XWPFDocument doc=newxwpfdocument(OPCPackage.open(newfileinputstream(filename));
List paragraphList=doc.getParagraphs();
用于(XWPF段落:段落列表){
if((para.getStyle()!=null)和&(para.getNumFmt()!=null)){
对于(XWPFRun:para.getRuns()){
String text=run.text();
text=text.replaceAll(text,“replacement”+text);
run.setText(文本,0);
}
}
}
doc.write(新文件输出流(“文件路径/输出文件名”);
}捕获(例外e){
e、 printStackTrace();
}
}
}

如果您想将内容保存到同一个文件中,可以更改
doc.write(新文件输出流(“输入文件/输入文件名的路径”)

看起来是Excel的,而不是Word的!谢谢你的回复。虽然您给出了在excel工作表中定义样式的答案,但需要获取并应用旧ms office.doc文件中使用的相同样式。我正在寻找一种方法,可以获取应用于doc文件中每个文本的样式。一旦我得到了样式,在创建文档文件的新副本(包含修改过的内容)时应用样式就很容易了。很抱歉,我误导了您。我已经添加了格式化Ms Word文档的新答案,请检查…这看起来是Excel,而不是Word!谢谢你的回复。虽然您给出了在excel工作表中定义样式的答案,但需要获取并应用旧ms office.doc文件中使用的相同样式。我正在寻找一种方法,可以获取应用于doc文件中每个文本的样式。一旦我得到了样式,在创建文档文件的新副本(包含修改过的内容)时应用样式就很容易了。很抱歉,我误导了您。我已经添加了格式化Ms Word文档的新答案,请检查…您好,您可以帮助我在页面中添加寄宿生,而不仅仅是一个段落。提前谢谢。嗨,你能帮我把寄宿生添加到页面上而不仅仅是一个段落吗。Th