Java POI excel插入图片

	

下面的例子是基于POI工具包, 对xlsx的excel进行修改的例子, 就是对原始excel再第7列插入了一列图片和每一条数据对应的.

图片插入部分注解比较详细, 这里不再写了.


	private static Map<String, File> getQRCode() {
		 Map<String, File> files = Maps.newHashMap();
		File f = new File("D:\\mnt\\sell\\qrcode500x500");
		File[] qrcodes = f.listFiles();
		for (File q : qrcodes) {
			files.put(q.getName().substring(0, q.getName().indexOf(".")), q);
		}
		return files;
	}
	
	
	/**
	 * 二维码贴入excel
	 * @param args
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public static void main(String[] args) throws FileNotFoundException, IOException {
		XSSFWorkbook  wb = new XSSFWorkbook(new FileInputStream(new File("D:\\mnt\\sell\\goods-information.xlsx")));
		XSSFSheet sheet = wb.getSheetAt(0);
		//sheet画图管理工具, 每个sheet维持一个
		XSSFDrawing patriarch = sheet.createDrawingPatriarch();
		//数据行数
		int n = sheet.getPhysicalNumberOfRows();
		
		Map<String, Integer> nameIndex = addPicture2Workbook(wb);
		String qrcodeName;
		for (int i = 1; i < n; i++) {
			qrcodeName = String.format("%s[%s]", sheet.getRow(i).getCell(0).getStringCellValue(),
					sheet.getRow(i).getCell(4).getStringCellValue());
			if (nameIndex.containsKey(qrcodeName)) {
				sheet.getRow(i).setHeightInPoints(150);//设置行高
				sheet.setColumnWidth(6, 30*256);//设置列宽, 第一个参数是列索引, 第二个是列宽单位是一个字符宽度的1/256, 这里相当于30字符宽度
				System.out.println("create picture :" + qrcodeName);
				//8个参数解释:  下面说的座标是cell内座标, cell中左上角为(x,y)->(0,0)位置
				//dx1 图片左上角所在x座标  (起始cell)
				//dy1 图片左上角所在y 座标  (起始cell)
				//dx2 图片右下角所在x座标 (结束cell)
				//dy2 图片右下角所在y座标 (结束cell)
				//col1 图片起始cell所在的列
				//row1 图片起始cell所在的行
				//col2 图片结束cell所在的列
				//row2 图片结束cell所在的行
				//下面图片左上角位于是第i行第6列, 右下角位于第i+1行第7列
				XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0,6, i, 7, i+1);
				anchor.setAnchorType(3);
				//插入图片, 第一个参数, 图片位置, 第二个参数是图片索引, 就是通过addPicture加入到webbook内的图片, 按照加入顺序, 
				//图片索引从0开始
				patriarch.createPicture(anchor, nameIndex.get(qrcodeName));
			}
		}
		//另存
		 FileOutputStream fileOut = new FileOutputStream(new File("D:\\mnt\\sell\\goods-2.xlsx"));
		 wb.write(fileOut);
		 fileOut.close();
	}
	private static Map<String, Integer> addPicture2Workbook(XSSFWorkbook wb) throws FileNotFoundException, IOException {
		Map<String, File> qr = getQRCode();
		Map<String, Integer> indx = Maps.newHashMap();
		int i = 0;
		for (Entry<String, File> kv : qr.entrySet()) {
			wb.addPicture(new FileInputStream(kv.getValue()), XSSFWorkbook.PICTURE_TYPE_PNG);
			indx.put(kv.getKey(), i);
			i++;
		}
		System.out.println("pictures : " + indx.size());
		return indx;
	}
	

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章