java docx文件处理作业代码

读取student.xslx里面的数据,根据预设的student.docx模板,生成学生具体的信息文档,最后转化为pdf文档。
整个程序可以分成多个步骤,或者整合为一个程序。

student.xslx:
在这里插入图片描述
student.docx:
在这里插入图片描述
注意java读docx模板可能出现问题:
可能是docx内部标签的问题,先将模板转化为xml再修改标签。
代码:

  1. CreateBarcode
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import org.krysalis.barcode4j.impl.code39.Code39Bean;
import org.krysalis.barcode4j.impl.upcean.EAN13Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;

public class CreateBarcode {
    
    

	public static void generateFile(String msg, String path) {
    
    
		File file = new File(path);
		try {
    
    
			Code39Bean bean = new Code39Bean();
			//EAN13Bean bean = new EAN13Bean();

			// dpi精度
			final int dpi = 150;
			// module宽度
			//bean.setModuleWidth(0.2);
			final double width = UnitConv.in2mm(2.0f / dpi);
			bean.setWideFactor(3);
			bean.setModuleWidth(width);
			bean.doQuietZone(false);

			String format = "image/png";
			// 输出到流
			BitmapCanvasProvider canvas = new BitmapCanvasProvider(new FileOutputStream(file), format, dpi,
					BufferedImage.TYPE_BYTE_BINARY, false, 0);

			// 生成条形码
			bean.generateBarcode(canvas, msg);

			//结束绘制
			canvas.finish();

		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
}

  1. ReadWriteExcelFile
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadWriteExcelFile
{
    
    
  public static void readXLSXFile(Map<String, Object> param) throws IOException
  {
    
    
    InputStream ExcelFileToRead = new FileInputStream("C:/Users/86187/desktop/student.xlsx");
    XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);

    XSSFSheet sheet = wb.getSheetAt(0);
    XSSFRow row;
    XSSFCell cell;

    Iterator rows = sheet.rowIterator();

    while (rows.hasNext())
    {
    
    
      row = (XSSFRow) rows.next();
      Iterator cells = row.cellIterator();
      int cnt=0;
      while (cells.hasNext())
      {
    
    
        cell = (XSSFCell) cells.next();

        if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
        {
    
    
          if(cnt==0)param.put("{name}",cell.getStringCellValue());
          else if(cnt==1)param.put("{sex}",cell.getStringCellValue());
          else if(cnt==2)param.put("{number}",cell.getStringCellValue());
          //System.out.println(cell.getStringCellValue());
          cnt++;
        }
      }
      //System.out.println();
    }

  }

}
  1. WriteTemplate
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.BodyElementType;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.IBodyElement;
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;

public class WriteTemplate {
    
    

	public static void main(String[] args) throws Exception{
    
    
		// TODO Auto-generated method stub
		XWPFDocument doc = openDocx("C:/Users/86187/desktop/student1.docx");//导入模板文件
		Map<String, Object> params = new HashMap<String, Object>();//文字类 key-value
		Map<String,String> picParams = new HashMap<String,String>();//图片类 key-url
		
		ReadWriteExcelFile.readXLSXFile(params);
		/*
		Iterator<String> it=params.keySet().iterator();
		while(it.hasNext()) {
			String key=it.next();
			System.out.println(key+" "+params.get(key));
		}
		*/
		
		String xuehao=params.get("{number}").toString();
		CreateBarcode.generateFile(xuehao,"C:/Users/86187/desktop/zhangsan.png");
		
		picParams.put("{barcode}", "C:/Users/86187/desktop/zhangsan.png");
		
		List<IBodyElement> ibes = doc.getBodyElements();
		for (IBodyElement ib : ibes) {
    
    
			if (ib.getElementType() == BodyElementType.TABLE) {
    
    
				replaceTable(ib, params, picParams, doc);
			}
			if (ib.getElementType() == BodyElementType.PARAGRAPH)
				replaceRun(ib,picParams,doc);
		}
		
		writeDocx(doc, new FileOutputStream("C:/Users/86187/desktop/student2.docx"));//输出
		System.out.println("Successfully written");
	}
	
	public static XWPFDocument openDocx(String url) {
    
    
		InputStream in = null;
		try {
    
    
			in = new FileInputStream(url);
			XWPFDocument doc = new XWPFDocument(in);
			return doc;
		} catch (FileNotFoundException e) {
    
    
			e.printStackTrace();
		} catch (IOException e) {
    
    
			e.printStackTrace();
		} finally {
    
    
			if (in != null) {
    
    
				try {
    
    
					in.close();
				} catch (IOException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	public static void writeDocx(XWPFDocument outDoc, OutputStream out) {
    
    
		try {
    
    
			outDoc.write(out);
			out.flush();
			if (out != null) {
    
    
				try {
    
    
					out.close();
				} catch (IOException e) {
    
    
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
    
    
			e.printStackTrace();
		}
	}
	
	private static Matcher matcher(String str) {
    
    
		Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(str);
		return matcher;
	}
	
	/**
	 * 写入image
	 * @param run
	 * @param imgFile
	 * @param doc
	 * @throws InvalidFormatException
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void replacePic(XWPFRun run,  String imgFile,  XWPFDocument doc) throws Exception {
    
    
		int format;
		if (imgFile.endsWith(".emf"))
			format = Document.PICTURE_TYPE_EMF;
		else if (imgFile.endsWith(".wmf"))
			format = Document.PICTURE_TYPE_WMF;
		else if (imgFile.endsWith(".pict"))
			format = Document.PICTURE_TYPE_PICT;
		else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg"))
			format = Document.PICTURE_TYPE_JPEG;
		else if (imgFile.endsWith(".png"))
			format = Document.PICTURE_TYPE_PNG;
		else if (imgFile.endsWith(".dib"))
			format = Document.PICTURE_TYPE_DIB;
		else if (imgFile.endsWith(".gif"))
			format = Document.PICTURE_TYPE_GIF;
		else if (imgFile.endsWith(".tiff"))
			format = Document.PICTURE_TYPE_TIFF;
		else if (imgFile.endsWith(".eps"))
			format = Document.PICTURE_TYPE_EPS;
		else if (imgFile.endsWith(".bmp"))
			format = Document.PICTURE_TYPE_BMP;
		else if (imgFile.endsWith(".wpg"))
			format = Document.PICTURE_TYPE_WPG;
		else {
    
    
			System.err.println(
					"Unsupported picture: " + imgFile + ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
			return;
		}
		if(imgFile.startsWith("http")||imgFile.startsWith("https")){
    
    
			run.addPicture(new URL(imgFile).openConnection().getInputStream(), format, "rpic",Units.toEMU(100),Units.toEMU(100));
		}else{
    
    
			run.addPicture(new FileInputStream(imgFile), format, "rpic",Units.toEMU(120),Units.toEMU(50));
		}
	}
	
	/**
	 * 替换表格内占位符
	 * @param para 表格对象
	 * @param params 文字替换map
	 * @param picParams 图片替换map
	 * @param indoc
	 * @throws Exception 
	 */
	public static void replaceTable(IBodyElement para ,Map<String, Object> params, 
			Map<String, String> picParams, XWPFDocument indoc)
			throws Exception {
    
    
		Matcher matcher;
		XWPFTable table;
		List<XWPFTableRow> rows;
		List<XWPFTableCell> cells;
		table = (XWPFTable) para;
		rows = table.getRows();
		for (XWPFTableRow row : rows) {
    
    
			cells = row.getTableCells();
			int cellsize = cells.size();
			int cellcount = 0;
			for(cellcount = 0; cellcount<cellsize;cellcount++){
    
    
				XWPFTableCell cell = cells.get(cellcount);
				String runtext = "";
				List<XWPFParagraph> ps = cell.getParagraphs();
				for (XWPFParagraph p : ps) {
    
    
					for(XWPFRun run : p.getRuns()){
    
    
						runtext = run.text();
						//matcher = matcher(runtext);
						//if (matcher.find()) {
    
    
							if (picParams != null) {
    
    
								for (String pickey : picParams.keySet()) {
    
    
									if (runtext.equals(pickey)) {
    
    
										run.setText("",0);
										replacePic(run, picParams.get(pickey), indoc);
										//System.out.println("replace pic");
									}
								}
							}
							if (params != null) {
    
    
								for (String pickey : params.keySet()) {
    
    
									if (runtext.equals(pickey)) {
    
    
										run.setText(params.get(pickey)+"",0);
										//System.out.println("replace string");
									}
								}
							}
						//}
					}
				}
			}
		}
	}

	public static void replaceRun(IBodyElement para ,Map<String, String> picParams, XWPFDocument indoc)throws Exception {
    
    
		XWPFParagraph temp = (XWPFParagraph) para;
		for(XWPFRun run : temp.getRuns()){
    
    
			for (String pickey : picParams.keySet()) {
    
    
					run.setText("",0);
					replacePic(run, picParams.get(pickey), indoc);
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/DwenKing/article/details/109334242