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;
	}
	

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