精华内容
下载资源
问答
  • java poi导出word文档DEMO

    2017-08-24 17:18:55
    java poi导出word文档DEMO
  • 昨天晚上被壳妹,威逼利诱,做点小东西,其中就有一个POI导出Word文档。并且最好不要用freemarker模板导出word文档,只好手动来一个工具类了。供参考学习显示界面49da6226c7fb4e8492c610d0af3103fa-WX...

    昨天晚上被壳妹,威逼利诱,做点小东西,其中就有一个POI导出Word文档。并且最好不要用freemarker模板导出word文档,只好手动来一个工具类了。

    供参考学习

    显示界面

    49da6226c7fb4e8492c610d0af3103fa-WX201706141301502x.png

    49da6226c7fb4e8492c610d0af3103fa-WX201706141301502x.png

    控制层代码

    public class ExportController {

    private static Logger logger = LoggerFactory.getLogger(ExportController.class);

    @RequestMapping("index")

    public String index(HttpServletRequest request, HttpServletResponse response) {

    /**

    * context 为以html样式导出到word文档里

    */

    String context = " \n" +

    "\n" +

    "\n" +

    " \n" +

    "\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" +

    " \n" +

    " \n" +

    " \"2\"align=\"center\"height=\"900px\"width=\"600px\"bordercolor=\"black\">\n" +

    " \"table\"style=\"height: 200px;\">\n" +

    " \n" +

    "\n" +

    " \n" +

    " \n" +

    " \"width: 50%;\" align=\"center\"> \n" +

    " 分 析 报 告\n" +

    " Failure Analysis Report\n" +

    " 名称:黑壳网\n" +

    "\"http://www.bhusk.com\">http:\\\\www.bhusk.com" +

    " \n" +

    " \n" +

    "\n" +

    "\n";

    /**

    * 创建工具类实例

    */

    ExportUtil exportUtil = new ExportUtil();

    /**

    * 调用~~~ 导出word成功

    */

    exportUtil.exportWord(request, response, context);

    return "index";

    }

    util类代码

    /**

    * POI导出word文档 无插件

    * Created by kzyuan on 2017/6/14.

    */

    public class ExportUtil {

    private static final Logger logger = LoggerFactory.getLogger(ExportUtil.class);

    public void exportWord(HttpServletRequest request, HttpServletResponse response, String content) {

    try {

    byte b[] = content.getBytes("utf-8"); //这里是必须要设置编码的,不然导出中文就会乱码。

    ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中

    /**

    * 关键地方

    * 生成word格式

    */

    POIFSFileSystem poifs = new POIFSFileSystem();

    DirectoryEntry directory = poifs.getRoot();

    DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);

    //输出文件

    String fileName = "wordFileName";

    request.setCharacterEncoding("utf-8");

    response.setContentType("application/msword");//导出word格式

    response.addHeader("Content-Disposition", "attachment;filename=" +

    new String((fileName + ".doc").getBytes(),

    "UTF-8"));

    OutputStream ostream = response.getOutputStream();

    poifs.writeFilesystem(ostream);

    bais.close();

    ostream.close();

    } catch (Exception e) {

    logger.error("导出出错:%s", e.getMessage());

    }

    }

    }

    源代码-GitHub

    展开全文
  • Java POI导出Word文档

    2017-06-18 23:40:54
    本文章来源 POI导出Word文档—黑壳网昨天晚上被壳妹,威逼利诱,做点小东西,其中就有一个POI导出Word文档。并且最好不要用freemarker模板导出word文档,只好手动来一个工具类了。 供参考学习显示界面 控制层代码...

    本文章来源 POI导出Word文档—黑壳网

    昨天晚上被壳妹,威逼利诱,做点小东西,其中就有一个POI导出Word文档。并且最好不要用freemarker模板导出word文档,只好手动来一个工具类了。
    供参考学习

    显示界面
    49da6226c7fb4e8492c610d0af3103fa-WX201706141301502x.png

    控制层代码

        public class ExportController {
    
          private static Logger logger = LoggerFactory.getLogger(ExportController.class);
    
          @RequestMapping("index")
          public String index(HttpServletRequest request, HttpServletResponse response) {
    
              /**
              * context 为以html样式导出到word文档里
              */
              String context = " \n" +
                      "\n" +
                      "\n" +
                      "  \n" +
                      "\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" +
                      "  \n" +
                      "  \n" +
                      "  \"2\"align=\"center\"height=\"900px\"width=\"600px\"bordercolor=\"black\">\n" +
                      "    \"table\"style=\"height: 200px;\">\n" +
                      "      \n" +
                      "\n" +
                      "    \n" +
                      "    \n" +
                      "       \"width: 50%;\" align=\"center\"> \n" +
                      "        分  析  报  告\n" +
                      "        Failure Analysis Report\n" +
                      "        名称:黑壳网\n" +
                      "\"http://www.bhusk.com\">http:\\\\www.bhusk.com" +
                      "       \n" +
                      "  \n" +
                      "\n" +
                      "\n";
    
        /**
        * 创建工具类实例
        */
        ExportUtil exportUtil = new ExportUtil();
    
        /**
        * 调用~~~ 导出word成功
        */
        exportUtil.exportWord(request, response, context);
    
         return "index";
      }

    util类代码

    /**
     * POI导出word文档 无插件
     * Created by kzyuan on 2017/6/14.
     */
    public class ExportUtil {
    
       private static final Logger logger = LoggerFactory.getLogger(ExportUtil.class);
    
       public void exportWord(HttpServletRequest request, HttpServletResponse response, String content) {
    
              try {
    
                  byte b[] = content.getBytes("utf-8"); //这里是必须要设置编码的,不然导出中文就会乱码。
        ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
    
        /**
       * 关键地方
       * 生成word格式
       */
        POIFSFileSystem poifs = new POIFSFileSystem();
        DirectoryEntry directory = poifs.getRoot();
        DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
        //输出文件
        String fileName = "wordFileName";
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/msword");//导出word格式
        response.addHeader("Content-Disposition", "attachment;filename=" +
                          new String((fileName + ".doc").getBytes(),
        "UTF-8"));
    
        OutputStream ostream = response.getOutputStream();
        poifs.writeFilesystem(ostream);
        bais.close();
        ostream.close();
        } catch (Exception e) {
                  logger.error("导出出错:%s", e.getMessage());
        }
        }
    }

    https://github.com/ykz200/POIExportWord”>源代码-GitHub

    展开全文
  • Java POI导出Word文档详解

    万次阅读 热门讨论 2019-08-28 14:58:06
    一、POI 生成导出Word样式 二、详细代码 pom.xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version...

    一、POI 生成导出Word样式

    二、详细代码

    pom.xml

    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi</artifactId>
    			<version>3.14</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi-ooxml</artifactId>
    			<version>3.14</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi-ooxml-schemas</artifactId>
    			<version>3.14</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi-scratchpad</artifactId>
    			<version>3.14</version>
    		</dependency>

    Controller

    	/**
    	 * 导出解译标志Word
    	 * @param id 
    	 * @return 
    	 * @author ygc 
    	 * @throws IOException 
    	 */
    	@Transactional(propagation=Propagation.SUPPORTS)
    	@ResponseBody
    	@RequestMapping("/ExportInterpretationSignsWord")
    	public  ResponseEntity<byte[]>  ExportInterpretationSignsWord(@RequestParam String token,HttpServletRequest request,
    		HttpServletResponse response,
    		@RequestParam int id) throws IOException{
    		response.setContentType("text/html;charset=UTF-8");   
    	    response.setHeader("Content-type", "application/json;charset=UTF-8");
    	    if(RedisPool.checkToken(token)==false) {
    	    	return null;
    	    }
    //		JsonResultInfo info=new JsonResultInfo(); 
    		 ResponseEntity<byte[]> temp=buildService.ExportInterpretationSignsWordById(id);
    //		info.setCode(200); 
    //		info.setData(temp); 
    //		info.setResult("成功"); 
    //		info.setMessage("导出解译标志Word"); 
    //		String r = JSON.toJSONString(info,SerializerFeature.WriteMapNullValue); 
    //		response.setContentType("text/json"); 
    //		response.getWriter().print(r); 	
    		return temp; 
    	}
    	

    Service

    	public 	 ResponseEntity<byte[]>  ExportInterpretationSignsWordById(int id) throws IOException {
    		LtinterpretationsignsjbxxExtends temp = buildMapper.findInterpretationSignsWordInfoById(id);
    		   XWPFDocument doc = new XWPFDocument();  
    	        XWPFParagraph para;  
    	        XWPFRun run;  
    	        //创建表格  
    	        XWPFTable table  = doc.createTable(8,4);  
    	        table.setCellMargins(3, 5, 3, 5);  
    //	        table.addNewCol();//添加新列  
    //	        table.createRow();//添加新行  
    	        String[] title1 = new String[]{"编号"," ","项目类型"," "};  
    	        String[] title2 = new String[]{"调查日期"," ","建设状态"," "};  
    	        XWPFTableRow row;  
    	        XWPFTableCell cell;  
    	        CTTcPr cellPr;  
    	        for(int j=0;j<8;j++){  
    	            row = table.getRow(j);  
    	            
    	            row.setHeight(600);     
    	            
    	            //第一行
    	            for(int i=0;i<title1.length;i++){      
    	            	  //创建单元格
    	            	  cell = row.getCell(i);  
    	     	       	  //单元格属性
    	    	          cellPr = cell.getCTTc().addNewTcPr();  
    	    	          //设置宽度
    	    	          cellPr.addNewTcW().setW(BigInteger.valueOf(5000)); 
    	    	          //垂直居中 
    	         		  cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);
    	    	          //第一个段落
    	    	    	  para = cell.getParagraphs().get(0);  
    	    	    	  //设置对齐方式
    	    	          para.setAlignment(ParagraphAlignment.CENTER);  
    	    	          //段落的对齐方式 1左 2中 3右 4往上 左 不可写0和负数
    	    	          para.setFontAlignment(2);
    	    	          //一个XWPFRun代表具有相同属性的一个区域:一段文本
    	                  run = para.createRun();
    	                  //设置字体
    	                  run.setFontFamily("仿宋"); 
    	                  //设置字体大小
    	                  run.setFontSize(13);  
    	                  if(j==0) {
    	                	  //字体宽
    //	                    run.setBold(true);  
    	                	  
    	                	  if(i==1) {
    	                		  title1[i]=temp.getXmnumber();
    	                	  		run = para.createRun();  
    		                		run.setFontSize(11); 
    	                		  run.setText(title1[i]);  
    	                	  }
    	                	  if(i==3) {
    	                		  title1[i]=temp.getXmtype();
    	                	  		run = para.createRun();  
    		                		run.setFontSize(11); 
    	                		  run.setText(title1[i]);  
    	                	  }
    	                
    		                	if(i==2) {
    		                        run.setText(title1[i]); 
    		                	}
    		                	if(i==0) {
    		                        run.setText(title1[i]); 
    		                	}
    	                    
    	                  }
    	            }    
    	            //第二行
    	            
    	            if(j==1){  
    	            	  for(int y=0;y<4;y++){ 
    	            	  if(y==0) {
    	            		  cell = row.getCell(0); 
    	                      cellPr = cell.getCTTc().addNewTcPr();  
    	                      cellPr.addNewTcW().setW(BigInteger.valueOf(5000));  
    	                	  para = cell.getParagraphs().get(0);  
    	                      para.setAlignment(ParagraphAlignment.CENTER);  
    	                      para.setFontAlignment(2);
    	                      run = para.createRun();             
    	                      run.setFontFamily("仿宋");  
    	                      run.setFontSize(13);  
    	                      run.setText("扰动类型");    
    	            	  }
    	            	  if(y==1) {
    	            		  cell = row.getCell(y); 
    	            		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART); 
    	            		  cell.setText(temp.getXmexcitation());
    	            	  }else {
    	            		  cell = row.getCell(y); 
    	                      cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
    	            	  }
    	                	  
    	                    
    	                  }
    	        
    	            }
    	            if(j==2){ 
    	          	  for(int y=0;y<4;y++){ 
    	          		  if(y==0) {
    	          			 cell = row.getCell(0); 
    	                     cellPr = cell.getCTTc().addNewTcPr();  
    	                     cellPr.addNewTcW().setW(BigInteger.valueOf(5000));  
    	               	      para = cell.getParagraphs().get(0);  
    	                     para.setAlignment(ParagraphAlignment.CENTER);  
    	                     para.setFontAlignment(2);
    	                     run = para.createRun();             
    	                     run.setFontFamily("仿宋");  
    	                     run.setFontSize(13);  
    	                     run.setText("项目名称");  
    	          		  }
    	            	  if(y==1) {
    	            		  cell = row.getCell(y); 
    	            	
    	            		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART); 
    	            		  cell.setText(temp.getXmname());
    	            	  }else {
    	            		  cell = row.getCell(y); 
    	                      cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
    	            	  }
    	          	  }
    	            	 
    	               
    	              }  
    	            for(int i=0;i<title2.length;i++){               
    	          	  cell = row.getCell(i);  
    	                cellPr = cell.getCTTc().addNewTcPr();  
    	                cellPr.addNewTcW().setW(BigInteger.valueOf(5000));  
    	                para = cell.getParagraphs().get(0);  
    	                para.setAlignment(ParagraphAlignment.CENTER);  
    	                para.setFontAlignment(2);
    	                run = para.createRun();             
    	                run.setFontFamily("仿宋");  
    	                run.setFontSize(13);  
    	                if(j==3) {
    	                	if(i==1) {
    	                		title2[i]=CommonUtil.transformDate(CommonUtil.getSysDate(temp.getXminvestigationdate())) ;
    	                		run = para.createRun();  
    	                		run.setFontSize(11); 
    	                        run.setText(title2[i]); 
    	                	}
    	                	if(i==3){
    	                		title2[i]=temp.getXmstate();
    	                		run = para.createRun();  
    	                		run.setFontSize(11); 
    	                        run.setText(title2[i]);
    	                	}
    	                	if(i==2) {
    	                        run.setText(title2[i]); 
    	                	}
    	                	if(i==0) {
    	                        run.setText(title2[i]); 
    	                	}
    	             
    	                }
    	             } 
    	            if(j==4){ 
    	          	  for(int y=0;y<4;y++){ 
    	          		  if(y==0) {
    	          		  	  cell = row.getCell(0); 
    	         	       	 //单元格属性
    	         	          cellPr = cell.getCTTc().addNewTcPr();  
    	         	          //设置宽度
    	         	          cellPr.addNewTcW().setW(BigInteger.valueOf(5000));  
    	         	          //第一个段落
    	         	    	  para = cell.getParagraphs().get(0);  
    	         	    
    	         	    	  //设置对齐方式
    	         	          para.setAlignment(ParagraphAlignment.CENTER);  
    	         	          //居中
    	         	          para.setFontAlignment(2);
    	         	      
    	         	          run = para.createRun();             
    	         	          run.setFontFamily("仿宋");  
    	         	          run.setFontSize(13);      
    	                       run.setText("详细地址");  
    	          		  }
    	              	  if(y==1) {
    	            		  cell = row.getCell(y); 	 
    	            		
    	            		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART); 
    	            		  cell.setText(temp.getXmdetailaddress());
    	              	  }else {
    	            		  cell = row.getCell(y); 
    	                      cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
    	            	  }
    	          	  }
    		     
    	           }  
    	            if(j==5){ 
    	            	//String imgPath="E:\\design_file_info_path\\设计文件\\2.jpg";
    	         
    	            	  for(int y=0;y<4;y++){ 
    	            		  if(y==0) {
    	            			  cell = row.getCell(y); 
    	                		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
    	                		  List<XWPFParagraph> paragraphs = cell.getParagraphs();
    	                	        XWPFParagraph newPara = paragraphs.get(0);
    	                	        XWPFRun imageCellRunn = newPara.createRun();
    	                	        System.out.println(temp.getXmimgpath()+File.separator+temp.getXmimgname()+"图片路径");
    	                	        File image = new File(temp.getXmimgpath()+File.separator+temp.getXmimgname());
    	                            if(!image.exists()){
    	                                continue;
    	                            }
    	                            try (FileInputStream is = new FileInputStream(temp.getXmimgpath()+File.separator+temp.getXmimgname())) {
    	                                imageCellRunn.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, image.getName(), Units.toEMU(160), Units.toEMU(160)); // 200x200 pixels
    	                            }catch (Exception e){
    	                                e.printStackTrace();
    	                            }
    	            		  }
    	            		  if(y==1) {
    	            			  cell = row.getCell(y); 
    	            			   cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
    	            	
    	            		  }
    	               		  if(y==2) {
    	               			  cell = row.getCell(y); 
    	                		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);   
    	                	
    	                		  cellPr = cell.getCTTc().addNewTcPr();  
    	             	          //设置宽度
    	             	          cellPr.addNewTcW().setW(BigInteger.valueOf(5000));  
    	             	          //第一个段落
    	             	    	  para = cell.getParagraphs().get(0);  
    	             	    
    	             	    	  //设置对齐方式
    	             	          para.setAlignment(ParagraphAlignment.LEFT);  
    	             	          //居左
    	             	          para.setFontAlignment(1);
    	             	         run = para.createRun();  
    	             	          run.addBreak();
    	             	          run.addBreak();
    	             	   	     cell.setText("(1)照片拍摄位置经纬度:");
    	             	          run = para.createRun();  
    	             	          run.addBreak();
    	             	          run.addBreak();
    	             	          cell.setText("    经度:"+temp.getXmlngdu()+"°"+temp.getXmlngfen()+"′"+temp.getXmlngmiao()+"″");
    	             	         run = para.createRun();  
    	            	          run.addBreak();
    	            	          run.addBreak();
    	            	          cell.setText("    纬度:"+temp.getXmlatdu()+"°"+temp.getXmlatfen()+"′"+temp.getXmlatmiao()+"″");
    	              	         run = para.createRun();  
    	             	          run.addBreak();
    	             	          run.addBreak();
    	             	          cell.setText("(2)照片拍摄时间:"+CommonUtil.transformDate(CommonUtil.getSysDate(temp.getXmpictime())));
    	             	         run = para.createRun();  
    	             	          run.addBreak();
    	             	          run.addBreak();
    	             	         cell.setText(null);
    
    	            		  }
    	            		  if(y==3) {
    	            			  cell = row.getCell(y); 
    	            			   cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
    	            		
    	            		  }
    	
    	            	  }
    
    	            }
    	            if(j==6){ 	
    	        		//String imgPath="E:\\design_file_info_path\\设计文件\\3.jpg";
    	          	  for(int y=0;y<4;y++){ 
    	        		  if(y==0) {
    	        			  cell = row.getCell(y); 
    	            		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
    	            		  List<XWPFParagraph> paragraphs = cell.getParagraphs();
    	            	        XWPFParagraph newPara = paragraphs.get(0);
    	            	        XWPFRun imageCellRunn = newPara.createRun();
    	            	        File image = new File(temp.getXmmiddleaddress()+File.separator+temp.getXmmiddlepicname());
    	                        if(!image.exists()){
    	                            continue;
    	                        }
    	                        try (FileInputStream is = new FileInputStream(temp.getXmmiddleaddress()+File.separator+temp.getXmmiddlepicname())) {
    	                            imageCellRunn.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, image.getName(), Units.toEMU(160), Units.toEMU(160)); // 200x200 pixels
    	                        }catch (Exception e){
    	                            e.printStackTrace();
    	                        }
    	        		  }
    	        		  if(y==1) {
    	        			  cell = row.getCell(y); 
    	        			   cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
    	        		  }
    	           		  if(y==2) {
    	           			  cell = row.getCell(y); 
                    		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);   
                    	
                    		  cellPr = cell.getCTTc().addNewTcPr();  
                 	          //设置宽度
                 	          cellPr.addNewTcW().setW(BigInteger.valueOf(5000));  
                 	          //第一个段落
                 	    	  para = cell.getParagraphs().get(0);  
                 	    
                 	    	  //设置对齐方式
                 	          para.setAlignment(ParagraphAlignment.LEFT);  
                 	          //居左
                 	          para.setFontAlignment(1);
                 	         run = para.createRun();  
                	          run.addBreak();
                	          run.addBreak();
                 	   	      cell.setText("(1)中分辨率影像类型:"+temp.getXmmiddletype());
                 	          run = para.createRun();  
                 	          run.addBreak();
                 	          run.addBreak();
                 	          cell.setText("(2)中分辨率影像成像时间:"+CommonUtil.transformDate(CommonUtil.getSysDate(temp.getXmmiddletime())));
                 	          run = para.createRun();  
                	          run.addBreak();
                	          run.addBreak();
                	          cell.setText("(3)中分辨率影像空间分辨率:"+temp.getXmmiddleresolution());
                  	          run = para.createRun();  
                 	          run.addBreak();
                 	          run.addBreak();
                 	          cell.setText("(4)中分辨率影像特征:"+temp.getXmmiddletype());
                 	         run = para.createRun();  
                	          run.addBreak();
                	          run.addBreak();
                	         cell.setText(null);
    	        		  }
    	        		  if(y==3) {
    	        			  cell = row.getCell(y); 
    	        			   cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
    	        		  }
    	        	  }
    	            }
    	            if(j==7){ 	
    	        	//	String imgPath="E:\\design_file_info_path\\设计文件\\4.jpg";
    	        		
    	          	  for(int y=0;y<4;y++){ 
    	        		  if(y==0) {
    	        			  cell = row.getCell(y); 
    	            		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
    	            		  List<XWPFParagraph> paragraphs = cell.getParagraphs();
    	            	        XWPFParagraph newPara = paragraphs.get(0);
    	            	        XWPFRun imageCellRunn = newPara.createRun();
    	            	        System.out.println(temp.getXmhighaddress()+File.separator+temp.getXmhighpicname());
    	            	        File image = new File(temp.getXmhighaddress(),temp.getXmhighpicname());
    	            	        System.out.println(image.getAbsolutePath());
    	            	        if(!image.exists()){
    	                            continue;
    	                        }
    	                        try (FileInputStream is = new FileInputStream(image)) {
    	                            
    	                        	imageCellRunn.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, image.getName(), Units.toEMU(160), Units.toEMU(160)); // 200x200 pixels
    	                        }catch (Exception e){
    	                            e.printStackTrace();
    	                        }
    	        		  }
    	        		  if(y==1) {
    	        			  cell = row.getCell(y); 
    	        			   cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
    	        		  }
    	           		  if(y==2) {
    	           			  cell = row.getCell(y); 
                    		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);   
                    	
                    		  cellPr = cell.getCTTc().addNewTcPr();  
                 	          //设置宽度
                 	          cellPr.addNewTcW().setW(BigInteger.valueOf(5000));  
                 	          //第一个段落
                 	    	  para = cell.getParagraphs().get(0);  
                 	    
                 	    	  //设置对齐方式
                 	          para.setAlignment(ParagraphAlignment.LEFT);  
                 	          //居左
                 	          para.setFontAlignment(1);
                 	         run = para.createRun();  
                	          run.addBreak();
                	          run.addBreak();
                 	   	     cell.setText("(1)高分辨率影像类型:"+temp.getXmhightype());
                 	          run = para.createRun();  
                 	          run.addBreak();
                 	          run.addBreak();
                 	          cell.setText("(2)高分辨率影像成像时间:"+CommonUtil.transformDate(CommonUtil.getSysDate(temp.getXmhightime())));
                 	         run = para.createRun();  
                	          run.addBreak();
                	          run.addBreak();
                	          cell.setText("(3)高分辨率影像空间分辨率:"+temp.getXmhighresolution());
                  	         run = para.createRun();  
                 	          run.addBreak();
                 	          run.addBreak();
                 	          cell.setText("(4)高分辨率影像特征:"+temp.getXmhighfeature());
                 	         run = para.createRun();  
                	          run.addBreak();
                	          run.addBreak();
                	         cell.setText(null);
    	           		  }
    	        		  if(y==3) {
    	        			  cell = row.getCell(y); 
    	        			   cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
    	        		  }
    	        	  }
    	            }
    	        }  
    	        String fileName="解析标志基本信息.doc";
    	        String path=Commons.INTERPRETATION_SIGNS_WORD+File.separator+fileName;
    	    	File storeDirectory = new File(Commons.INTERPRETATION_SIGNS_WORD);
    			if (!storeDirectory.exists() &&!storeDirectory.isDirectory()) {
    				storeDirectory.mkdirs();
    			}
    	        File file = new File(path);
    	        FileOutputStream  os = new FileOutputStream(file);  
    	        doc.write(os);  
    	        if(os!=null){  
    	            try{  
    	                os.close();  
    	                System.out.println("文件已输出!");  
    	            	HttpHeaders headers = new HttpHeaders();
    	    			// 下载显示的文件名,解决中文名称乱码问题
    	    			String downloadFielName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
    	    			// 通知浏览器以attachment(下载方式)打开
    	    			headers.setContentDispositionFormData("attachment", downloadFielName);
    	    			// application/octet-stream : 二进制流数据(最常见的文件下载)。
    	    			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	    			return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    	            }  
    	            catch(IOException e){  
    	                e.printStackTrace();  
    	            }  
    	        }  
    		
    		
    		return null;
    	}

    三、导出Word测试工具--测试版

    package com.kero99.utils;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.math.BigInteger;
    import java.util.List;
    
    import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    import org.apache.poi.util.Units;
    import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
    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 org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
    import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
    import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;
    
    /**
     * 导出word
     * @author ygc
     */
    public class ExportWord {
    	public static void main(String[] args) throws IOException, InvalidFormatException {
    	    XWPFDocument doc = new XWPFDocument();  
            XWPFParagraph para;  
            XWPFRun run;  
            //创建表格  
            XWPFTable table  = doc.createTable(8,4);  
            table.setCellMargins(3, 5, 3, 5);  
    //        table.addNewCol();//添加新列  
    //        table.createRow();//添加新行  
            String[] title1 = new String[]{"编号"," ","项目类型"," "};  
            String[] title2 = new String[]{"调查日期"," ","建设状态"," "};  
            XWPFTableRow row;  
            XWPFTableCell cell;  
            CTTcPr cellPr;  
            for(int j=0;j<8;j++){  
                row = table.getRow(j);  
                
                row.setHeight(600);     
                
                //第一行
                for(int i=0;i<title1.length;i++){      
                	  //创建单元格
                	  cell = row.getCell(i);  
         	       	  //单元格属性
        	          cellPr = cell.getCTTc().addNewTcPr();  
        	          //设置宽度
        	          cellPr.addNewTcW().setW(BigInteger.valueOf(5000)); 
        	          //垂直居中 
             		  cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);
        	          //第一个段落
        	    	  para = cell.getParagraphs().get(0);  
        	    	  //设置对齐方式
        	          para.setAlignment(ParagraphAlignment.CENTER);  
        	          //段落的对齐方式 1左 2中 3右 4往上 左 不可写0和负数
        	          para.setFontAlignment(2);
        	          //一个XWPFRun代表具有相同属性的一个区域:一段文本
                      run = para.createRun();
                      //设置字体
                      run.setFontFamily("仿宋"); 
                      //设置字体大小
                      run.setFontSize(11);  
                      if(j==0) {
                    	  //字体宽
    //                    run.setBold(true);  
                          run.setText(title1[i]);  
                      }
                }    
                //第二行
                
                if(j==1){  
                	  for(int y=0;y<4;y++){ 
                	  if(y==0) {
                		  cell = row.getCell(0); 
                          cellPr = cell.getCTTc().addNewTcPr();  
                          cellPr.addNewTcW().setW(BigInteger.valueOf(5000));  
                    	  para = cell.getParagraphs().get(0);  
                          para.setAlignment(ParagraphAlignment.CENTER);  
                          para.setFontAlignment(2);
                          run = para.createRun();             
                          run.setFontFamily("仿宋");  
                          run.setFontSize(13);  
                          run.setText("扰动类型");    
                	  }
                	  if(y==1) {
                		  cell = row.getCell(y); 
                		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART); 
                	  }else {
                		  cell = row.getCell(y); 
                          cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
                	  }
                    	  
                        
                      }
            
                }
                if(j==2){ 
              	  for(int y=0;y<4;y++){ 
              		  if(y==0) {
              			 cell = row.getCell(0); 
                         cellPr = cell.getCTTc().addNewTcPr();  
                         cellPr.addNewTcW().setW(BigInteger.valueOf(5000));  
                   	      para = cell.getParagraphs().get(0);  
                         para.setAlignment(ParagraphAlignment.CENTER);  
                         para.setFontAlignment(2);
                         run = para.createRun();             
                         run.setFontFamily("仿宋");  
                         run.setFontSize(13);  
                         run.setText("项目名称");  
              		  }
                	  if(y==1) {
                		  cell = row.getCell(y); 
                		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART); 
                	  }else {
                		  cell = row.getCell(y); 
                          cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
                	  }
              	  }
                	 
                   
                  }  
                for(int i=0;i<title2.length;i++){               
              	  cell = row.getCell(i);  
                    cellPr = cell.getCTTc().addNewTcPr();  
                    cellPr.addNewTcW().setW(BigInteger.valueOf(5000));  
                    para = cell.getParagraphs().get(0);  
                    para.setAlignment(ParagraphAlignment.CENTER);  
                    para.setFontAlignment(2);
                    run = para.createRun();             
                    run.setFontFamily("仿宋");  
                    run.setFontSize(13);  
                    if(j==3) {
                      
                        run.setText(title2[i]);  
                    }
                 } 
                if(j==4){ 
              	  for(int y=0;y<4;y++){ 
              		  if(y==0) {
              		  	  cell = row.getCell(0); 
             	       	 //单元格属性
             	          cellPr = cell.getCTTc().addNewTcPr();  
             	          //设置宽度
             	          cellPr.addNewTcW().setW(BigInteger.valueOf(5000));  
             	          //第一个段落
             	    	  para = cell.getParagraphs().get(0);  
             	    
             	    	  //设置对齐方式
             	          para.setAlignment(ParagraphAlignment.CENTER);  
             	          //居中
             	          para.setFontAlignment(2);
             	      
             	          run = para.createRun();             
             	          run.setFontFamily("仿宋");  
             	          run.setFontSize(13);      
                           run.setText("详细地址");  
              		  }
                  	  if(y==1) {
                		  cell = row.getCell(y); 
                		  
                		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART); 
                	  }else {
                		  cell = row.getCell(y); 
                          cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
                	  }
              	  }
    	     
               }  
                if(j==5){ 
                	String imgPath="E:\\design_file_info_path\\设计文件\\2.jpg";
                	  for(int y=0;y<4;y++){ 
                		  if(y==0) {
                			  cell = row.getCell(y); 
                    		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                    		  List<XWPFParagraph> paragraphs = cell.getParagraphs();
                   
                    	        XWPFParagraph newPara = paragraphs.get(0);   
                    	        XWPFRun imageCellRunn = newPara.createRun();
                    	        File image = new File(imgPath);
                                if(!image.exists()){
                                    continue;
                                }
                                try (FileInputStream is = new FileInputStream(imgPath)) {
                                    imageCellRunn.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, image.getName(), Units.toEMU(180), Units.toEMU(180)); // 200x200 pixels
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                                
                    
                		  }
                		  if(y==1) {
                			  cell = row.getCell(y); 
                			   cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
                		
                		  }
                   		  if(y==2) {               	
                   			  cell = row.getCell(y); 
                    		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);   
                    		  cell.setText("(1)照片拍摄位置经纬度:");
                    		  cellPr = cell.getCTTc().addNewTcPr();  
                 	          //设置宽度
                 	          cellPr.addNewTcW().setW(BigInteger.valueOf(5000));  
                 	          //第一个段落
                 	    	  para = cell.getParagraphs().get(0);  
                 	    
                 	    	  //设置对齐方式
                 	          para.setAlignment(ParagraphAlignment.LEFT);  
                 	          //居左
                 	          para.setFontAlignment(1);
                 	      
                 	          run = para.createRun();  
                 	          run.addBreak();
                 	          run.addBreak();
                 	          cell.setText("    经度:");
    //            	          run.addBreak();
    //             	          run.addBreak();
                 	         run = para.createRun();  
                	          run.addBreak();
                	          run.addBreak();
                	          cell.setText("    经度:");
                  	         run = para.createRun();  
                 	          run.addBreak();
                 	          run.addBreak();
                 	          cell.setText("(2)照片拍摄时间:");
    //               	          run.addBreak();
    //             	          run.addBreak();
    //             	          cell.setText("(2)照片拍摄时间:");
    //             	          run.addBreak();
    //             	          cell.setText("纬度:");
    //                           run.setText("(1)照片拍摄位置经纬度:    经度:");  
    //                           run.addCarriageReturn();
    //                           run.addBreak();//换行
    
                   		  }
                		  if(y==3) {
                			  cell = row.getCell(y); 
                			   cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
                		  
                		  }
                	  }
    
                }
                if(j==6){ 	
            		String imgPath="E:\\design_file_info_path\\设计文件\\3.jpg";
              	  for(int y=0;y<4;y++){ 
            		  if(y==0) {
            			  cell = row.getCell(y); 
                		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                		  List<XWPFParagraph> paragraphs = cell.getParagraphs();
                	        XWPFParagraph newPara = paragraphs.get(0);
                	        XWPFRun imageCellRunn = newPara.createRun();
                	        File image = new File(imgPath);
                            if(!image.exists()){
                                continue;
                            }
                            try (FileInputStream is = new FileInputStream(imgPath)) {
                                imageCellRunn.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, image.getName(), Units.toEMU(180), Units.toEMU(180)); // 200x200 pixels
                            }catch (Exception e){
                                e.printStackTrace();
                            }
            		  }
            		  if(y==1) {
            			  cell = row.getCell(y); 
            			   cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
            		  }
               		  if(y==2) {
            			  cell = row.getCell(y); 
                		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            		  }
            		  if(y==3) {
            			  cell = row.getCell(y); 
            			   cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
            		  }
            	  }
                }
                if(j==7){ 	
            		String imgPath="E:\\design_file_info_path\\设计文件\\4.jpg";
              	  for(int y=0;y<4;y++){ 
            		  if(y==0) {
            			  cell = row.getCell(y); 
                		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                		  List<XWPFParagraph> paragraphs = cell.getParagraphs();
                	        XWPFParagraph newPara = paragraphs.get(0);
                	        XWPFRun imageCellRunn = newPara.createRun();
                	        File image = new File(imgPath);
                            if(!image.exists()){
                                continue;
                            }
                            try (FileInputStream is = new FileInputStream(imgPath)) {
                                imageCellRunn.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, image.getName(), Units.toEMU(180), Units.toEMU(180)); // 200x200 pixels
                            }catch (Exception e){
                                e.printStackTrace();
                            }
            		  }
            		  if(y==1) {
            			  cell = row.getCell(y); 
            			   cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
            		  }
               		  if(y==2) {
            			  cell = row.getCell(y); 
                		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            		  }
            		  if(y==3) {
            			  cell = row.getCell(y); 
            			   cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
            		  }
            	  }
                }
            }  
            
            OutputStream os = new FileOutputStream("E:\\wordTest3.doc");  
            doc.write(os);  
            if(os!=null){  
                try{  
                    os.close();  
                    System.out.println("文件已输出!");  
                }  
                catch(IOException e){  
                    e.printStackTrace();  
                }  
            }  
    	}
    }
    

    测试版-导出样式

    四、关键代码

    1. 合并单元格
    2. 单元格空格
    3. 调整字体大小

     

     

    1.合并单元格

                	  if(y==1) {
                		  cell = row.getCell(y); 
                		  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART); 
                	  }else {
                		  cell = row.getCell(y); 
                          cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE); 
                	  }

    2.单元格回车

                              run = para.createRun();  
                 	          run.addBreak();
                 	          run.addBreak();
                 	          cell.setText("    经度:");
                 	          run = para.createRun();  
                	          run.addBreak();
                	          run.addBreak();
                	          cell.setText("    经度:");

    3.调整字体大小

    	                        if(i==1) {
                                    //这块查询的日期
                                    title2[i]=CommonUtil.transformDate(
                                    CommonUtil.getSysDate(temp.getXminvestigationdate())) ;
    	                		run = para.createRun();  
    	                		run.setFontSize(11); 
    	                        run.setText(title2[i]); 
    	                	}
    	                	if(i==3){
                                  //查询的状态
    	                		title2[i]=temp.getXmstate();
    	                		run = para.createRun();  
    	                		run.setFontSize(11); 
    	                        run.setText(title2[i]);
    	                	}
    	                	if(i==2) {
    	                        run.setText(title2[i]); 
    	                	}
    	                	if(i==0) {
    	                        run.setText(title2[i]); 
    	                	}

     

     

    展开全文
  • java poi 导出word后参数未替换而是一个括号 } 是因为调试中途修改原word模板某些参数,导致某些缓存跟不上,即使再编译刷新也不生效。 所以当你核实参数名和格式没写错的话,重启项目就好了。 ...

    java poi 导出word后参数未替换而是一个括号 }

    是因为调试中途修改原word模板某些参数,导致某些缓存跟不上,即使再编译刷新也不生效。
    所以当你核实参数名和格式没写错的话,重启项目就好了。

    展开全文
  • java poi导出word之后再次对此wrod添加内容 ``` List<String> l = new ArrayList(); l.add("亲爱的xx你好"); l.add("录取你入我校xx专业"); l.add("请凭此通知书来报到"); l.add("具体时间,具体地点...
  • Java POI导出word文件及生成表格

    千次阅读 2020-03-25 17:04:37
    HWPF是处理 Microsoft Word 97(-2007) .doc文件格式,它还为较旧的Word 6和Word 95文件格式... XWPF是处理 Word 2007 .docx文件格式,包含在poi-ooxml-XXX.jar中。 虽然HWPF和XWPF提供类似的功能,但目前两者...
  • 加上最近项目上也遇到了要使用java导出word多表格的问题. 开始网上找的例子大多是使用xml来操作word,后来多翻了点文章完成了word多表导出. 参考文章: 网上找的表格导出基础工具类 有使用到上面链接里面的...
  • java POI导出Word文档

    2018-01-12 16:49:33
    run.setText("Java POI 生成word文件。"); run.setColor("696969"); run.setFontSize(16); //设置段落背景颜色 CTShd cTShd = run.getCTR().addNewRPr().addNewShd(); cTShd.setVal(STShd.CLEAR); ...
  • Word07Template word07Template = new Word07Template(); XWPFDocument doc = word07Template.generateDoc(inputStream, conf, loops, result); //end this //自动生成对应文本内容后,下面代码生成图片...
  • /** * 导出Word表格 * @author Saffi */ @RequestMapping("exportWord.action") public void exportWord(HttpServletResponse response) throws IOException { try { List<Entity>...
  • Java使用POI导出Word文档的操作教程,poiword一、主要pom依赖org.apache.poipoi-ooxml3.16二、需要导出word模板三、相关导出代码package com.iflytek.chy;import java.io.FileInputStream;import java.io....
  • import java.awt.Point; import java.awt.Rectangle; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.util.ArrayList; ...
  • 最近项目中需要用到数据的导出Word,本在项目中使用POI将数据导入到Word,代码示例非常简洁,代码包含pom依赖文件,下载解压即可到本地调试运行。
  • java POI生成word.zip

    2019-08-16 17:49:26
    java POI导出word文档代码,可参考具体代码,两个类,根据自己情况参考 java POI导出word文档代码,可参考具体代码,两个类,根据自己情况参考
  • java使用poi导出word并且带图片

    千次阅读 2019-12-04 15:27:28
    最近在开发中有按照模板导出word的需求,并且把echarts图例附到word里,我开始使用freework取ftl模板的,不过由于转换麻烦,需定义好格式xml再转为ftl文件所以改为使用poi取word模板直接赋值的方式,并且通过拼接...
  • POI导出word文档模版直接用于下载和html页面展示
  • POI导出word

    千次阅读 2019-01-03 13:45:05
    poi导出word 最近有一个项目需要用做导出word的功能,刚开始用的是poi,开始写的时候才发现poi对于word的支持真的是少的可怜,还是推荐大家用xml或者别的来做导出word,本次功能分两篇博客展现如果用需要用poi的...
  • 暑期在杭州实习了两个月,主要是使用vue+SpringMVC进行...在网上搜索了许多方法,了解到要导出word文件,其实办法由很多,如jacob,java2word,FreeMarker,Apatch POI等等。 本文采用的是Apatch POI中的一系列API,它...
  • 【踩坑笔记】java使用poi导出word文档换行 poi导出word,没有使用模板替换方式,而是设置创建段落和表格生成word。表格内容填充的段落没有自动换行,不方便阅览,测试了很多方法终于实现! 贴上原始代码 ...
  • java poi word导出

    2021-04-27 16:09:52
    java poi word导出 (含有文字,图像) 导出word效果如下: 思路:建立预期导出word效果,设置为模板,然后填充对应信息,注意,加粗,居中等一些图片,文字格式预先设置好。然后进行文字或者图片填充即可; 1.将word...
  • java工具类POI导出word

    2017-12-09 16:40:00
    1、新建一个word,里面填写内容,如: 2、导出wordjava类 ... * POI导出word测试 * @throws Exception */ @RequestMapping(value="exportApplyForm") public void exportApplyForm(HttpServletRespon...
  • java poi3.17导出word

    2020-08-31 16:35:34
    org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.a

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 4,560
精华内容 1,824
关键字:

javapoi导出word

java 订阅