java 操作word表格_java 操作word表格

该代码示例展示了如何使用 Apache POI 库在 Java 中读取、修改和填充 Word 文档模板。主要功能包括替换文本内容、处理表格数据,并能根据给定的 Map 数据结构和 List 数据填充模板。适用于批量生成定制化 Word 报告的场景。
摘要由CSDN通过智能技术生成

/*

* 文 件 名:  MSWordPoi4.java

* 版    权:  Sunny Technologies Co., Ltd. Copyright YYYY-YYYY,  All rights reserved

* 描    述: 

* 修 改 人:  L.Hao

* 修改时间:  2014-8-8

* 跟踪单号: 

* 修改单号: 

* 修改内容: 

*/

package com.fms.xx.util;

/**

*

*

*

* @author  L.Hao

* @version  [版本号, 2014-8-8]

* @see  [相关类/方法]

* @since  [产品/模块版本]

*/

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import org.apache.poi.POIXMLDocument;

import org.apache.poi.POIXMLTextExtractor;

import org.apache.poi.hwpf.HWPFDocument;

import org.apache.poi.hwpf.model.FieldsDocumentPart;

import org.apache.poi.hwpf.usermodel.Field;

import org.apache.poi.hwpf.usermodel.Fields;

import org.apache.poi.hwpf.usermodel.Range;

import org.apache.poi.openxml4j.opc.OPCPackage;

import org.apache.poi.xwpf.extractor.XWPFWordExtractor;

import org.apache.poi.xwpf.usermodel.XWPFDocument;

import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import org.apache.poi.xwpf.usermodel.XWPFRun;

import org.apache.poi.xwpf.usermodel.XWPFTable;

import org.apache.poi.xwpf.usermodel.XWPFTableCell;

import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import com.fms.scm.contract.bean.OrderSupplyBean;

import com.fms.xx.common.FileInfoUtil;

import com.fms.xx.common.FtpDownLoad;

public class MSWordPoi4

{

/**

* @param args

*/

public static void main(String[] args)

{

Map map = new HashMap();

map.put("${sub}", "湖南大学");

map.put("${item2.school}", "湖南大学");

map.put("${item2.address}", "湖南");

//        map.put("${item1.name}", "王五1");

//        map.put("${item1.numberStudent}", "编号002");

//        map.put("${item1.sex}", "男2");

//        map.put("${item1.age}", "19");

String srcPath = "F:\\template.doc";

readwriteWord(map,srcPath,"");

}

/**

* 实现对word读取和修改操作

*

* @param filePath  word模板路径和名称

* @param realPath  tomcat路径

* @param map 待填充的数据,从数据库读取

*/

public static FileInfoUtil readwriteWord( Map map,String filePath,String filename)

{

// 读取word模板

// String fileDir = new

// File(base.getFile(),"http://www.cnblogs.com/http://www.cnblogs.com/../doc/").getCanonicalPath();

FileInputStream in = null;

FileInfoUtil fileInfoUtil = new FileInfoUtil();

//FTP下载文件开始

String desFileDir = filePath+"/"+filename;

FtpDownLoad ftp = new FtpDownLoad(desFileDir); //下载到目标路径下

ArrayList list = new ArrayList();

String ftpFileName = filename.substring(filename.indexOf("/")); //文件名

list.add(ftpFileName);

ftp.getFile(list);

//结束

try

{

in = new FileInputStream(new File(desFileDir));//读取word模板

}

catch (FileNotFoundException e1)

{

e1.printStackTrace();

//返回服务器上没有模板的提示

fileInfoUtil.setRelativePath("hasnoTemp");

return fileInfoUtil;

}

HWPFDocument hdt = null;

try

{

hdt = new HWPFDocument(in);

}

catch (IOException e1)

{

e1.printStackTrace();

}

Fields fields = hdt.getFields();

Iterator it = fields.getFields(FieldsDocumentPart.MAIN).iterator();

while (it.hasNext())

{

System.out.println(it.next().getType());

}

//读取word文本内容

Range range = hdt.getRange();

System.out.println(range.text());

// 替换文本内容

for (Map.Entry entry : map.entrySet())

{

range.replaceText(entry.getKey(), entry.getValue());

}

ByteArrayOutputStream ostream = new ByteArrayOutputStream();

String fileName = "" + System.currentTimeMillis();

fileName += ".doc";

FileOutputStream out = null;

try

{

File file =new File(filePath+"/template");

//如果文件夹不存在则创建

if  (!file.exists())

{

file.mkdir();

}

out = new FileOutputStream(filePath+"/template/" + fileName, true);

fileInfoUtil.setFileName(fileName);

fileInfoUtil.setRelativePath("template/"+fileName);

fileInfoUtil.setAbsolutePath(filePath+"/template/");

}

catch (FileNotFoundException e)

{

e.printStackTrace();

}

try

{

hdt.write(ostream);

}

catch (IOException e)

{

e.printStackTrace();

}

// 输出字节流

try

{

out.write(ostream.toByteArray());

}

catch (IOException e)

{

e.printStackTrace();

}

try

{

out.close();

}

catch (IOException e)

{

e.printStackTrace();

}

try

{

ostream.close();

}

catch (IOException e)

{

e.printStackTrace();

}

return fileInfoUtil;

}

/**

* 实现对word及word中表格读取和修改操作

*

* @param filePath  word模板路径和名称

* @param realPath  tomcat路径

* @param map 待填充的数据,从数据库读取

*/

public static FileInfoUtil readwriteTableWord(Map map,String filePath,String filename,List listSupply)

{

// 读取word模板

FileInputStream in = null;

FileInfoUtil fileInfoUtil = new FileInfoUtil();

//FTP下载文件开始

String desFileDir = filePath+"/"+filename;

FtpDownLoad ftp = new FtpDownLoad(desFileDir); //下载到目标路径下

ArrayList list = new ArrayList();

String ftpFileName = filename.substring(filename.indexOf("/")); //文件名

list.add(ftpFileName);

ftp.getFile(list);

//下载结束

//载入文档 替换开始

XWPFDocument document = null;

try

{

//替换普通文本

document = new XWPFDocument(POIXMLDocument.openPackage(desFileDir));

try

{

Iterator itPara = document.getParagraphsIterator();

while (itPara.hasNext()) {

XWPFParagraph paragraph = (XWPFParagraph) itPara.next();

List runs = paragraph.getRuns();

for (int i = 0; i < runs.size(); i++) {

String oneparaString = runs.get(i).getText(

runs.get(i).getTextPosition());

for (Map.Entry entry : map

.entrySet()) {

oneparaString = oneparaString.replace(

entry.getKey(), entry.getValue());

}

runs.get(i).setText(oneparaString, 0);

}

}

//给表格中写入值(物资前4条信息)

Iterator itTable = document.getTablesIterator();

ArrayList al = new ArrayList();

while (itTable.hasNext()) {

XWPFTable table = (XWPFTable) itTable.next();

int rcount = table.getNumberOfRows();  //行数

for (int i = 0; i < rcount; i++) {

XWPFTableRow row = table.getRow(i);

List cells = row.getTableCells();  //第i行的cell

//for(int k=0;k

int supplyCount = listSupply.size();

if(supplyCount<5){

if(i>0&&i

OrderSupplyBean supply = (OrderSupplyBean)listSupply.get(i-1);

cells.get(0).setText(String.valueOf(i));

cells.get(1).setText(supply.getSupplyNorms());

cells.get(2).setText(supply.getSupplyUnit());

cells.get(3).setText(supply.getOrderCount().toString());

cells.get(4).setText(supply.getPurchasePrice().toString());

cells.get(5).setText(supply.getPurchaseAmount().toString());

}

}else{

if(i>0&&i<5){

OrderSupplyBean supply = (OrderSupplyBean)listSupply.get(i-1);

cells.get(0).setText(String.valueOf(i));

cells.get(1).setText(supply.getSupplyNorms());

cells.get(2).setText(supply.getSupplyUnit());

cells.get(3).setText(supply.getOrderCount().toString());

cells.get(4).setText(supply.getPurchasePrice().toString());

cells.get(5).setText(supply.getPurchaseAmount().toString());

}

}

}

}

}

catch (Exception e)

{

e.printStackTrace();

}

}

catch (Exception e1)

{

e1.printStackTrace();

//返回服务器上没有模板的提示

fileInfoUtil.setRelativePath("hasnoTemp");

return fileInfoUtil;

}

String fileName = "" + System.currentTimeMillis();

//fileName += ".doc"; //2003

fileName += ".docx";  //2007

try

{

fileInfoUtil.setFileName(fileName);

fileInfoUtil.setRelativePath("template/"+fileName);

fileInfoUtil.setAbsolutePath(filePath+"/template/");

if(listSupply.size()>3){ //从第五个物资开始生成表格

//生成表格插入开始

XWPFTable table = document.createTable(1,7);

table.setWidth(800);

// 添加表头的元素    序号   型号  单位  数量  单价(元) 金额(元) 备注

XWPFTableRow tableRowOne = table.getRow(0);

tableRowOne.getCell(0).setText("序号");

tableRowOne.getCell(1).setText("型号");

tableRowOne.getCell(2).setText("单位");

tableRowOne.getCell(3).setText("数量");

tableRowOne.getCell(4).setText("单价(元)");

tableRowOne.getCell(5).setText("金额(元)");

tableRowOne.getCell(6).setText("备注");

for(int i=4;i

OrderSupplyBean supply = (OrderSupplyBean)listSupply.get(i);

XWPFTableRow tableRow_i = table.createRow();

tableRow_i.getCell(0).setText((i+1)+"");

tableRow_i.getCell(1).setText(supply.getSupplyNorms());

tableRow_i.getCell(2).setText(supply.getSupplyUnit());

tableRow_i.getCell(3).setText(supply.getOrderCount().toString());

tableRow_i.getCell(4).setText(supply.getPurchasePrice().toString());

tableRow_i.getCell(5).setText(supply.getPurchaseAmount().toString());

tableRow_i.getCell(6).setText("");

}

XWPFTableRow tableRowEnd = table.createRow();

tableRowEnd.setCantSplitRow(true);

}

//tableRowEnd.getCell(0).setText("备注:1.《技术协议》、《阀门数据表》作为本合同附件,与本合同具有同等法律效力。2.合同价含税费(17%增值税专用发票)、货物费、技术服务费、资料费、运费等。3.本合同货物本体及证明文件中不准带任何商标标识(包括铸字商标)。");

String outPath= filePath+"/template/" +"111"+fileName;  //此路径返回页面供下载

FileOutputStream fOut = new FileOutputStream(outPath);

document.write(fOut);

fOut.flush();

// 操作结束,关闭文件

fOut.close();

//生成表格插入结束

}

catch (Exception e)

{

e.printStackTrace();

}

return fileInfoUtil;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值