java實現導出doc文檔

之前只接觸過導出excel,當然項目中總會有一些特殊要求,比如這次甲方爸爸要求導出word文檔,代碼來了。

項目使用的是pom進行管理的,dependency包括下面幾個

		<!-- doc  -->
		<dependency>
		    <groupId>com.lowagie</groupId>
		    <artifactId>itext</artifactId>
		    <version>2.1.7</version>
		</dependency>
		<dependency>
			<groupId>com.lowagie</groupId>
			<artifactId>itext-rtf</artifactId>
			<version>2.1.7</version>
		</dependency>

下面是自己測試的demo

	public static void main(String[] args) {
		File f = new File("D:/test.doc");
		OutputStream fOut = null;
		try {
			fOut = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}
		List<String> assetCodeList = new ArrayList<String>();
		for (int i=0; i<10; i++) {
			assetCodeList.add("code" + i);
		}
		//批量導出資產編碼
		exPortQRCodes(assetCodeList, fOut);
	}

調用的方法是這個。

//這個只是一個基本的演示代碼,自己可以進行擴展
	void exPortQRCodes(List<String> assetCodeList, OutputStream fOut) {
		try {
			  //創建Document對象(word文檔)
			  Rectangle rectPageSize = new Rectangle(PageSize.A4);
			  rectPageSize = rectPageSize.rotate();
			  // 創建word文檔,並設置紙張的大小
			  Document doc = new Document(PageSize.A4);
			  
			  //建立一個書寫器與document對象關聯,通過書寫器可以將文檔寫入到輸出流中
			  RtfWriter2.getInstance(doc, fOut);
			  doc.open();
			  
			  if(assetCodeList == null || assetCodeList.size() == 0){
				  Paragraph context = new Paragraph("不存在資產信息");
				  // 正文格式對齊方式
				  context.setAlignment(Element.ALIGN_CENTER);
				  // 與上一段落(標題)的行距
				  context.setSpacingBefore(10);
				  doc.add(context);
				  doc.close();
				  return;
			  }
			  
			  int size = assetCodeList.size();
			  int cols = 3;
			  int tables = size/cols + (size%cols > 0 ? 1: 0);
			  for(int i = 0 ; i < tables; i++){
				  //表格設置(列、行)
				  Table table = new Table(cols, 2);
				  int[] withs = { 33, 33, 34};
				  //設置每列所佔比例
				  table.setWidths(withs);
				  //表格所佔頁面寬度
				  table.setWidth(100);
				  //居中顯示
				  table.setAlignment(Element.ALIGN_CENTER);
				  //自動填滿
				  table.setBorderWidth(5); // 邊框寬度  
				  table.setBorderColor(new Color(0, 125, 255)); // 邊框顏色  
				  table.setPadding(12);// 襯距,看效果就知道什麼意思了  
				  table.setSpacing(0);// 即單元格之間的間距  
				  table.setBorder(5);// 邊框
				  //寫入表格第一行的說明
				  for(int idx = 0; idx < cols; idx++){
					  Cell cell = null;
					  if(i*cols + idx >= size){
						 cell = new Cell("");
					  } else {
						  String title = "這個可以顯示出來的內容";
						  cell = new Cell(title);
					  }
					  cell.setVerticalAlignment(Element.ALIGN_CENTER);
					  cell.setHorizontalAlignment(Element.ALIGN_CENTER);
					  table.addCell(cell);
				  }
				  //寫入表格第二行的二維碼
				  for(int idx = 0; idx < cols; idx++){
					  Cell cell = null;
					  if(i*cols + idx >= size){
						 cell = new Cell("");
					  } else {
						  cell = new Cell("什麼東西");
					  }
					  cell.setVerticalAlignment(Element.ALIGN_CENTER);
					  cell.setHorizontalAlignment(Element.ALIGN_CENTER);
					  
					  table.addCell(cell);
				  }
				  doc.add(table);
			  }
			  doc.close();
		}  catch (Exception e) {
			e.printStackTrace();
		}
	}

如果是使用到項目當中,那麼需要下面的代碼,可以根據自己的需要進行修改

	@RequestMapping(value="/downloadQRcode",method=RequestMethod.POST)
	@ResponseBody
	public void downloadQRcode(HttpServletResponse response) throws IOException {
		OutputStream fOut = null;
		fOut = response.getOutputStream();
		String agent = (String)getHttpRequest().getHeader("USER-AGENT");
		String fileName = "二維碼_" + DateUtil.generateTime();
		
		if(agent!=null && agent.toLowerCase().indexOf("firefox")>0){
			fileName = firefoxFile(fileName);
		}else{
			fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
		}
		response.setContentType("application/vnd.ms-word");
		response.setHeader("content-disposition", "attachment;filename=" + fileName + ".doc");
		
		String code = this.getHttpRequest().getParameter("code");
		@SuppressWarnings({ "unchecked", "deprecation" })
		List<String> codes = JSONArray.toList(JSONArray.fromObject(code), String.class);
		List<XXX> assetCodeList = xxService.getxxCodes(codes);
		exPortQRCodes(assetCodeList, fOut);
	}

快樂編程

知識使我快樂

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