Java 操作World表格

新建一个表格

//XWPFDocument doc = new XWPFDocument();//创建一个5行5列的表格

XWPFTable table = doc.createTable(5, 5);//这里增加的列原本初始化创建的那5行在通过getTableCells()方法获取时获取不到,但通过row新增的就可以。//table.addNewCol();//给表格增加一列,变成6列

table.createRow(); //给表格新增一行,变成6行

List rows =table.getRows();//表格属性

CTTblPr tablePr =table.getCTTbl().addNewTblPr();//表格宽度

CTTblWidth width =tablePr.addNewTblW();

width.setW(BigInteger.valueOf(8000));

XWPFTableRow row;

Listcells;

XWPFTableCell cell;int rowSize =rows.size();intcellSize;for (int i=0; i

row=rows.get(i);//新增单元格

row.addNewTableCell();//设置行的高度

row.setHeight(500);//行属性//CTTrPr rowPr = row.getCtRow().addNewTrPr();//这种方式是可以获取到新增的cell的。//List list = row.getCtRow().getTcList();

cells =row.getTableCells();

cellSize=cells.size();for (int j=0; j

cell=cells.get(j);if ((i+j)%2==0) {//设置单元格的颜色

cell.setColor("ff0000"); //红色

} else{

cell.setColor("0000ff"); //蓝色

}//单元格属性

CTTcPr cellPr =cell.getCTTc().addNewTcPr();

cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);if (j == 3) {//设置宽度

cellPr.addNewTcW().setW(BigInteger.valueOf(3000));

}

cell.setText(i+ ", " +j);

}

}//文件不存在时会自动创建

OutputStream os = new FileOutputStream("D:\\table.docx");//写入文件

doc.write(os);this.close(os);

段落内容替换

/*** 替换段落里面的变量

*@parampara 要替换的段落

*@paramparams 参数*/

private void replaceInPara(XWPFParagraph para, Mapparams) {

Listruns;

Matcher matcher;if (this.matcher(para.getParagraphText()).find()) {

runs=para.getRuns();for (int i=0; i

XWPFRun run=runs.get(i);

String runText=run.toString();

matcher= this.matcher(runText);if(matcher.find()) {while ((matcher = this.matcher(runText)).find()) {

runText= matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));

}//直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,//所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。

para.removeRun(i);

para.insertNewRun(i).setText(runText);

}

}

}

}

直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。

//抽取 word docx文件中的图片

String path ="D://abc.docx";

File file= newFile(path);try{

FileInputStream fis= newFileInputStream(file);

XWPFDocument document= newXWPFDocument(fis);

XWPFWordExtractor xwpfWordExtractor= newXWPFWordExtractor(document);

String text=xwpfWordExtractor.getText();

System.out.println(text);

List picList =document.getAllPictures();for(XWPFPictureData pic : picList) {

System.out.println(pic.getPictureType()+ file.separator +pic.suggestFileExtension()+file.separator+pic.getFileName());byte[] bytev =pic.getData();

FileOutputStream fos= new FileOutputStream("D:\\abc\\docxImage\\"+pic.getFileName());

fos.write(bytev);

}

fis.close();

}catch(IOException e) {

e.printStackTrace();

}

}

多级标题结构

/*** 自定义样式方式写word,参考statckoverflow的源码

*

*@throwsIOException*/

public static void writeSimpleDocxFile() throwsIOException {

XWPFDocument docxDocument= newXWPFDocument();//老外自定义了一个名字,中文版的最好还是按照word给的标题名来,否则级别上可能会乱

addCustomHeadingStyle(docxDocument, "标题 1", 1);

addCustomHeadingStyle(docxDocument,"标题 2", 2);//标题1

XWPFParagraph paragraph =docxDocument.createParagraph();

XWPFRun run=paragraph.createRun();

run.setText("标题 1");

paragraph.setStyle("标题 1");//标题2

XWPFParagraph paragraph2 =docxDocument.createParagraph();

XWPFRun run2=paragraph2.createRun();

run2.setText("标题 2");

paragraph2.setStyle("标题 2");//正文

XWPFParagraph paragraphX =docxDocument.createParagraph();

XWPFRun runX=paragraphX.createRun();

runX.setText("正文");//word写入到文件

FileOutputStream fos = new FileOutputStream("D:/myDoc2.docx");

docxDocument.write(fos);

fos.close();

}/*** 增加自定义标题样式。这里用的是stackoverflow的源码

*

*@paramdocxDocument 目标文档

*@paramstrStyleId 样式名称

*@paramheadingLevel 样式级别*/

private static void addCustomHeadingStyle(XWPFDocument docxDocument, String strStyleId, intheadingLevel) {

CTStyle ctStyle=CTStyle.Factory.newInstance();

ctStyle.setStyleId(strStyleId);

CTString styleName=CTString.Factory.newInstance();

styleName.setVal(strStyleId);

ctStyle.setName(styleName);

CTDecimalNumber indentNumber=CTDecimalNumber.Factory.newInstance();

indentNumber.setVal(BigInteger.valueOf(headingLevel));//lower number > style is more prominent in the formats bar

ctStyle.setUiPriority(indentNumber);

CTOnOff onoffnull=CTOnOff.Factory.newInstance();

ctStyle.setUnhideWhenUsed(onoffnull);//style shows up in the formats bar

ctStyle.setQFormat(onoffnull);//style defines a heading of the given level

CTPPr ppr =CTPPr.Factory.newInstance();

ppr.setOutlineLvl(indentNumber);

ctStyle.setPPr(ppr);

XWPFStyle style= newXWPFStyle(ctStyle);//is a null op if already defined

XWPFStyles styles =docxDocument.createStyles();

style.setType(STStyleType.PARAGRAPH);

styles.addStyle(style);

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java操作表格文件,可以使用一些库或API来实现,比较常用的有Apache POI和OpenCSV。 1. Apache POI:它是一个用于操作Microsoft Office格式文件的Java库,包括Excel文件。你可以使用POI来读取、写入和修改Excel文件。 - 首先,你需要在项目中添加POI的依赖。在Maven项目中,可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> ``` - 读取Excel文件: ```java import org.apache.poi.ss.usermodel.*; try { Workbook workbook = WorkbookFactory.create(new File("path/to/excel/file.xlsx")); Sheet sheet = workbook.getSheetAt(0); // 获取第一个sheet for (Row row : sheet) { for (Cell cell : row) { // 处理单元格数据 String cellValue = cell.getStringCellValue(); System.out.println(cellValue); } } workbook.close(); } catch (IOException e) { e.printStackTrace(); } ``` - 写入Excel文件: ```java import org.apache.poi.ss.usermodel.*; Workbook workbook = new XSSFWorkbook(); // 创建新的工作簿 Sheet sheet = workbook.createSheet("Sheet1"); // 创建新的sheet Row row = sheet.createRow(0); // 创建第一行 Cell cell = row.createCell(0); // 创建第一个单元格 cell.setCellValue("Hello, World!"); try { FileOutputStream outputStream = new FileOutputStream("path/to/excel/file.xlsx"); workbook.write(outputStream); workbook.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } ``` 2. OpenCSV:它是一个用于读写CSV文件的Java库,CSV文件也可以看做是一种表格文件。 - 首先,你需要在项目中添加OpenCSV的依赖。在Maven项目中,可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.5.2</version> </dependency> ``` - 读取CSV文件: ```java import com.opencsv.CSVReader; try { CSVReader reader = new CSVReader(new FileReader("path/to/csv/file.csv")); String[] nextLine; while ((nextLine = reader.readNext()) != null) { for (String cell : nextLine) { // 处理单元格数据 System.out.println(cell); } } reader.close(); } catch (IOException e) { e.printStackTrace(); } ``` - 写入CSV文件: ```java import com.opencsv.CSVWriter; try { CSVWriter writer = new CSVWriter(new FileWriter("path/to/csv/file.csv")); String[] record = {"Hello", "World"}; writer.writeNext(record); writer.close(); } catch (IOException e) { e.printStackTrace(); } ``` 以上是使用Apache POI和OpenCSV两个库进行表格文件操作的基本示例,你可以根据自己的需求进行进一步的操作和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值