[转]利用POI组件 导入导出excel

[转]利用POI组件 导入导出excel

项目中经常遇到要将列表中的数据导出到excel中或是要将已经存在的excel文档的数据导入到数据库中。这里记录下在struts1.2中的用法。
1、从excel导入
Java代码 复制代码
  1. /**  
  2.      * 从处部excel文件中导入应急物资记录  
  3.      * @param mapping  
  4.      * @param form  
  5.      * @param request  
  6.      * @param response  
  7.      * @return  
  8.      */  
  9.     public ActionForward importMaterials(ActionMapping mapping, ActionForm form,   
  10.             HttpServletRequest request, HttpServletResponse response){   
  11.            
  12.         int beginRowIndex = 2;          //从excel中开始读取的起始行数   
  13.         int totalRows = 0;              //该excel表的总行数   
  14.         IUserProfile userPro = (IUserProfile) request.getSession().getAttribute(IUserProfile.SESSION_USERPROFILE_KEY);   
  15.            
  16.         ImportFileForm importFileForm = (ImportFileForm)form;   
  17.            
  18.         //读取要导入的文件   
  19.         FormFile file = importFileForm.getExcelfile();   
  20.         String title = file.getFileName().replaceAll(".xls""");   
  21.         logger.debug("标题是:"+title);   
  22.         try {   
  23.             //根据文件的输入流,创建对Excel工作簿文件的引用     
  24.             HSSFWorkbook  workbook  =  new HSSFWorkbook(file.getInputStream());   
  25.             //默认excel的书页(sheet)是"Sheet1"   
  26.             HSSFSheet  sheet  =  workbook.getSheetAt(0);     
  27.             //该excel表的总行数   
  28.             totalRows = sheet.getLastRowNum();   
  29.             logger.debug("输出总行数:"+totalRows);   
  30.                
  31.             //循环读取excel表格的每行记录,并逐行进行保存   
  32.             for(int i=beginRowIndex;i<=totalRows;i++){   
  33.                 HSSFRow  row  =  sheet.getRow(i);   
  34.                 //获取一行每列的数据   
  35.                 HSSFCell  materialNameCell      =  row.getCell((short)0);   
  36.                 HSSFCell  amountCell            =  row.getCell((short)1);   
  37.                 HSSFCell  orgCell               =  row.getCell((short)2);   
  38.                 HSSFCell  storePlaceCell        =  row.getCell((short)3);   
  39.                 HSSFCell  buyTimeCell           =  row.getCell((short)4);   
  40.                 HSSFCell  periodCell            =  row.getCell((short)5);   
  41.                 HSSFCell  principalNameCell     =  row.getCell((short)6);   
  42.                 HSSFCell  principalMobileCell   =  row.getCell((short)7);   
  43.                 HSSFCell  linkManCell           =  row.getCell((short)8);   
  44.                 HSSFCell  linkManMobileCell     =  row.getCell((short)9);   
  45.                    
  46.                 //将列数据赋给相关变量   
  47.                 String materialName = materialNameCell.getRichStringCellValue().getString();       
  48.                 String amount = amountCell.getRichStringCellValue().getString();   
  49.                 String orgName = orgCell.getRichStringCellValue().getString();                  String storePlace   = storePlaceCell.getRichStringCellValue().getString();   
  50.                 String buyTime          = "";          
  51.                 if(buyTimeCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){   
  52.                     buyTime = new Double(buyTimeCell.getNumericCellValue()).toString();   
  53.                 }else if(buyTimeCell.getCellType()==HSSFCell.CELL_TYPE_STRING){   
  54.                     buyTime = buyTimeCell.getRichStringCellValue().getString();   
  55.                 }   
  56.                 String period           = "";   
  57.                 if(periodCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){   
  58.                     period = new Double(periodCell.getNumericCellValue()).toString();   
  59.                 }else if(periodCell.getCellType()==HSSFCell.CELL_TYPE_STRING){   
  60.                     period = periodCell.getRichStringCellValue().getString();   
  61.                 }   
  62.                 String principalName= principalNameCell.getRichStringCellValue().getString();   
  63.                 String principalMobile= new Long((long)principalMobileCell.getNumericCellValue()).toString();   
  64.                 String linkMan          = linkManCell.getRichStringCellValue().getString();   
  65.                 String linkManMobile = new Long((long)linkManMobileCell.getNumericCellValue()).toString();     
  66.                    
  67.                 //保存当前行的数据   
  68.                 try{   
  69.                 saveMaterial(materialName,amount,orgName,storePlace,buyTime,period,principalName,principalMobile,linkMan,linkManMobile,userPro);   
  70.   
  71.                 }catch(Exception e){   
  72.                     throw e;   
  73.                 }   
  74.             }   //for end   
  75.             MessageDisplayService.disposeMessage(request, response,"导入文件成功");   
  76.         } catch (FileNotFoundException e) {   
  77.             MessageDisplayService.disposeMessage(request, response,"找不到文件");   
  78.         } catch (IOException e) {   
  79.             MessageDisplayService.disposeMessage(request, response,"导入文件失败,连接数据库失败");      
  80.         } catch(Exception e){   
  81.             e.printStackTrace();   
  82.             MessageDisplayService.disposeMessage(request, response,"导入文件失败,文档模板格式不正确");   
  83.         }   
  84.         return mapping.findForward("import_ok");    
  85.            
  86.     }  
/**
	 * 从处部excel文件中导入应急物资记录
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward importMaterials(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		
		int beginRowIndex = 2;			//从excel中开始读取的起始行数
		int totalRows = 0;				//该excel表的总行数
		IUserProfile userPro = (IUserProfile) request.getSession().getAttribute(IUserProfile.SESSION_USERPROFILE_KEY);
		
		ImportFileForm importFileForm = (ImportFileForm)form;
		
		//读取要导入的文件
		FormFile file = importFileForm.getExcelfile();
		String title = file.getFileName().replaceAll(".xls", "");
		logger.debug("标题是:"+title);
		try {
			//根据文件的输入流,创建对Excel工作簿文件的引用  
			HSSFWorkbook  workbook  =  new HSSFWorkbook(file.getInputStream());
			//默认excel的书页(sheet)是"Sheet1"
			HSSFSheet  sheet  =  workbook.getSheetAt(0);  
			//该excel表的总行数
			totalRows = sheet.getLastRowNum();
			logger.debug("输出总行数:"+totalRows);
			
			//循环读取excel表格的每行记录,并逐行进行保存
			for(int i=beginRowIndex;i<=totalRows;i++){
				HSSFRow  row  =  sheet.getRow(i);
				//获取一行每列的数据
				HSSFCell  materialNameCell 		=  row.getCell((short)0);
				HSSFCell  amountCell  			=  row.getCell((short)1);
				HSSFCell  orgCell  				=  row.getCell((short)2);
				HSSFCell  storePlaceCell  		=  row.getCell((short)3);
				HSSFCell  buyTimeCell			=  row.getCell((short)4);
				HSSFCell  periodCell			=  row.getCell((short)5);
				HSSFCell  principalNameCell  	=  row.getCell((short)6);
				HSSFCell  principalMobileCell	=  row.getCell((short)7);
				HSSFCell  linkManCell  			=  row.getCell((short)8);
				HSSFCell  linkManMobileCell		=  row.getCell((short)9);
				
				//将列数据赋给相关变量
				String materialName = materialNameCell.getRichStringCellValue().getString();	
				String amount = amountCell.getRichStringCellValue().getString();
				String orgName = orgCell.getRichStringCellValue().getString();					String storePlace 	= storePlaceCell.getRichStringCellValue().getString();
				String buyTime 			= "";		
				if(buyTimeCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
					buyTime = new Double(buyTimeCell.getNumericCellValue()).toString();
				}else if(buyTimeCell.getCellType()==HSSFCell.CELL_TYPE_STRING){
					buyTime = buyTimeCell.getRichStringCellValue().getString();
				}
				String period 			= "";
				if(periodCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
					period = new Double(periodCell.getNumericCellValue()).toString();
				}else if(periodCell.getCellType()==HSSFCell.CELL_TYPE_STRING){
					period = periodCell.getRichStringCellValue().getString();
				}
				String principalName= principalNameCell.getRichStringCellValue().getString();
				String principalMobile= new Long((long)principalMobileCell.getNumericCellValue()).toString();
				String linkMan 			= linkManCell.getRichStringCellValue().getString();
				String linkManMobile = new Long((long)linkManMobileCell.getNumericCellValue()).toString();	
				
				//保存当前行的数据
				try{
				saveMaterial(materialName,amount,orgName,storePlace,buyTime,period,principalName,principalMobile,linkMan,linkManMobile,userPro);

				}catch(Exception e){
					throw e;
				}
			}	//for end
			MessageDisplayService.disposeMessage(request, response,"导入文件成功");
		} catch (FileNotFoundException e) {
			MessageDisplayService.disposeMessage(request, response,"找不到文件");
		} catch (IOException e) {
			MessageDisplayService.disposeMessage(request, response,"导入文件失败,连接数据库失败");	
		} catch(Exception e){
			e.printStackTrace();
			MessageDisplayService.disposeMessage(request, response,"导入文件失败,文档模板格式不正确");
		}
		return mapping.findForward("import_ok"); 
		
	}



Java代码 复制代码
  1. /**  
  2.      * 将从excel中抽取的一行物资记录转换后存入数据库  
  3.      * @param userPro  
  4.      */  
  5.     private void saveMaterial(String materialName,   
  6.                                 String amount,   
  7.                                 String orgName,   
  8.                                 String storePlace,   
  9.                                 String buyTime,   
  10.                                 String period,   
  11.                                 String principalName,   
  12.                                 String principalMobile,   
  13.                                 String linkMan,   
  14.                                 String linkManMobile,   
  15.                                 IUserProfile userPro) throws Exception{   
  16.         MaterialForm form = new MaterialForm();   
  17.         form.setMaterialName(materialName);        
  18.         form.setAmount(amount);   
  19.         form.setOrgName(orgName);   
  20.         form.setStorePlace(storePlace);        
  21.         form.setBuyTime(buyTime);              
  22.         form.setPeriod(period);            
  23.         form.setPrincipalName(principalName);      
  24.         form.setPrincipalMobile(principalMobile);      
  25.         form.setLinkman(linkMan);              
  26.         form.setLinkmanMobile(linkManMobile);      
  27.         //保存   
  28.         materialManager.saveOrUpdate(form, userPro);   
  29.     }  
/**
	 * 将从excel中抽取的一行物资记录转换后存入数据库
	 * @param userPro
	 */
	private void saveMaterial(String materialName,
								String amount,
								String orgName,
								String storePlace,
								String buyTime,
								String period,
								String principalName,
								String principalMobile,
								String linkMan,
								String linkManMobile,
								IUserProfile userPro) throws Exception{
		MaterialForm form = new MaterialForm();
		form.setMaterialName(materialName);		
		form.setAmount(amount);
		form.setOrgName(orgName);
		form.setStorePlace(storePlace);		
		form.setBuyTime(buyTime);			
		form.setPeriod(period);			
		form.setPrincipalName(principalName);	
		form.setPrincipalMobile(principalMobile);	
		form.setLinkman(linkMan);			
		form.setLinkmanMobile(linkManMobile);	
		//保存
		materialManager.saveOrUpdate(form, userPro);
	}


2、从数据库导出到excel中
Java代码 复制代码
  1. /**  
  2.      * 根据条件导出excel(可选择导出项)  
  3.      * @param form  
  4.      * @param request  
  5.      * @param response  
  6.      * @throws IOException  
  7.      */  
  8.     public void exportStreetEvent(ActionForm form,HttpServletRequest request,HttpServletResponse response) throws IOException{   
  9.            
  10.            
  11.         HSSFWorkbook workbook = new HSSFWorkbook();   
  12.         int sheetRowNum = 0;             
  13.         XwzsEventQueryForm xwzsEventQueryForm = (XwzsEventQueryForm)form;   
  14.            
  15.         /**从库中取出相关数据**/  
  16.         List list12 = xwzsEventManager.getEventQuery(xwzsEventQueryForm,projections);          
  17.         List list = getEventExport(list12);     //将取出的列表格式化,不是必须   
  18.   
  19.         String title = "事件列表";   
  20.         // 创建工作表和标题   
  21.         HSSFSheet sheet = workbook.createSheet("event");   
  22.         // 设置标题栏合并区域   
  23.         Region r = new Region(0, (short00, (short12);   
  24.         ExportUtil.fillMergedRegion(workbook, sheet, r, title, workbook.createCellStyle());   
  25.         sheetRowNum++;   
  26.         // 设置列宽   
  27.         // 默认列宽   
  28.         sheet.setDefaultColumnWidth((short10);   
  29.         // 自定义列宽   
  30.         // sheet.autoSizeColumn((short)1);   
  31.         sheet.setColumnWidth((short)1, (short)(268*21));   
  32.         sheet.setColumnWidth((short)3, (short)(268*13));   
  33.         sheet.setColumnWidth((short)10, (short)(268*21));   
  34.         sheet.setColumnWidth((short)11, (short)(268*16));   
  35.   
  36.         // 设置字体格式   
  37.         HSSFFont font = workbook.createFont();   
  38.         font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);   
  39.         font.setFontName("仿宋_GB2312");   
  40.         font.setFontHeightInPoints((short12);   
  41.         // 创建格式模型   
  42.         HSSFCellStyle cs = workbook.createCellStyle();   
  43.         cs.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);   
  44.         cs.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);   
  45.         cs.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);   
  46.         cs.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);   
  47.         // 自动换行   
  48.         cs.setWrapText(true);   
  49.         // 上下居中   
  50.         cs.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);   
  51.         cs.setFont(font);   
  52.         // 创建数据项格式   
  53.         HSSFCellStyle cs1 = workbook.createCellStyle();   
  54.         cs1.setBorderTop(HSSFCellStyle.BORDER_THIN);   
  55.         cs1.setBorderLeft(HSSFCellStyle.BORDER_THIN);   
  56.         cs1.setBorderBottom(HSSFCellStyle.BORDER_THIN);   
  57.         cs1.setBorderRight(HSSFCellStyle.BORDER_THIN);   
  58.         cs1.setWrapText(true);   
  59.         cs1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);   
  60.         String[] titles = { "日期""期号""事发时间""首报时间""首报单位","地点","事件标题","类别","等级","领导现场指挥","区领导批示","报市应急办","处置中存在的问题","首报人","接电人" };   
  61.         HSSFRow dataTitleRow = sheet.createRow((short) sheetRowNum++);   
  62.   
  63.            
  64.         //获取用户选择的输出项   
  65.         for (int i = 0; i < titles.length; i++) {   
  66.             HSSFCell cell = dataTitleRow.createCell((short) i);   
  67.             cell.setCellType(HSSFCell.CELL_TYPE_STRING);   
  68.             cell.setCellValue(new HSSFRichTextString(titles[i]));   
  69.             cell.setCellStyle(cs);   
  70.         }   
  71.                
  72.         // 数据模型转换:创建表格数据   
  73.         for (int i = 0; i < list.size(); i++) {   
  74.             EventExport eventexport = (EventExport) list.get(i);   
  75.             HSSFRow dataRow = sheet.createRow((short) (i+sheetRowNum));   
  76.             HSSFCell celldate = dataRow.createCell((short0);   
  77.             HSSFCell cellqihao = dataRow.createCell((short1);   
  78.             HSSFCell cellhappentime = dataRow.createCell((short2);   
  79.             HSSFCell cellreporttime = dataRow.createCell((short3);   
  80.             HSSFCell cellreportdepart = dataRow.createCell((short4);   
  81.             HSSFCell celladdress = dataRow.createCell((short5);   
  82.             HSSFCell cellevent = dataRow.createCell((short6);   
  83.             HSSFCell celltype = dataRow.createCell((short7);   
  84.             HSSFCell cellgrade = dataRow.createCell((short8);   
  85.             HSSFCell cellcommand = dataRow.createCell((short9);   
  86.             HSSFCell cell1denote = dataRow.createCell((short10);   
  87.             HSSFCell cell1report = dataRow.createCell((short11);   
  88.             HSSFCell cell1problem = dataRow.createCell((short12);   
  89.             // 中文编码   
  90.             celldate.setCellValue(new HSSFRichTextString(eventexport.getDate()));   
  91.             cell2.setCellValue(new HSSFRichTextString(jinzhan.getDetailcontent()));   
  92.             cellhappentime.setCellValue(new HSSFRichTextString(eventexport.getHappentime()));   
  93.             cellreporttime.setCellValue(new HSSFRichTextString(eventexport.getReporttime()));   
  94.             cellreportdepart.setCellValue(new HSSFRichTextString(eventexport.getDepartment()));   
  95.             celladdress.setCellValue(new HSSFRichTextString(eventexport.getPlace()));   
  96.             cellevent.setCellValue(new HSSFRichTextString(eventexport.getEventcontent()));   
  97.             celltype.setCellValue(new HSSFRichTextString(eventexport.getEventtype()));   
  98.             cellgrade.setCellValue(new HSSFRichTextString(eventexport.getEventlevel()));   
  99.             cellcommand.setCellValue(new HSSFRichTextString(eventexport.getLocalleader()));   
  100.             cell1denote.setCellValue(new HSSFRichTextString(eventexport.getDenote()));   
  101.             cell1report.setCellValue(new HSSFRichTextString(eventexport.getReportflag()));   
  102.                    
  103.             // 设置各个列的格式   
  104.             celldate.setCellStyle(cs1);   
  105.             cellqihao.setCellStyle(cs1);   
  106.             cellhappentime.setCellStyle(cs1);   
  107.             cellreporttime.setCellStyle(cs1);   
  108.             cellreportdepart.setCellStyle(cs1);   
  109.             celladdress.setCellStyle(cs1);   
  110.             cellevent.setCellStyle(cs1);   
  111.             celltype.setCellStyle(cs1);   
  112.             cellgrade.setCellStyle(cs1);   
  113.             cellcommand.setCellStyle(cs1);   
  114.             cell1denote.setCellStyle(cs1);   
  115.             cell1report.setCellStyle(cs1);   
  116.             cell1problem.setCellStyle(cs1);   
  117.            
  118.         }   
  119.         //输出文件   
  120.         OutputStream out = response.getOutputStream();   
  121.         response.setCharacterEncoding("gbk");   
  122.         response.setContentType("application/x-msexcel");   
  123.         response.setHeader("Content-Disposition""attachment;filename="  
  124.                 + ExportUtil.UniC(title) + ".xls");   
  125.   
  126.         workbook.write(out);   
  127.         out.close();   
  128.     }  
/**
	 * 根据条件导出excel(可选择导出项)
	 * @param form
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void exportStreetEvent(ActionForm form,HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		
		HSSFWorkbook workbook = new HSSFWorkbook();
		int sheetRowNum = 0;	      
		XwzsEventQueryForm xwzsEventQueryForm = (XwzsEventQueryForm)form;
		
		/**从库中取出相关数据**/
		List list12 = xwzsEventManager.getEventQuery(xwzsEventQueryForm,projections);		
		List list = getEventExport(list12);		//将取出的列表格式化,不是必须

		String title = "事件列表";
		// 创建工作表和标题
		HSSFSheet sheet = workbook.createSheet("event");
		// 设置标题栏合并区域
		Region r = new Region(0, (short) 0, 0, (short) 12);
		ExportUtil.fillMergedRegion(workbook, sheet, r, title, workbook.createCellStyle());
		sheetRowNum++;
		// 设置列宽
		// 默认列宽
		sheet.setDefaultColumnWidth((short) 10);
		// 自定义列宽
		// sheet.autoSizeColumn((short)1);
		sheet.setColumnWidth((short)1, (short)(268*21));
		sheet.setColumnWidth((short)3, (short)(268*13));
		sheet.setColumnWidth((short)10, (short)(268*21));
		sheet.setColumnWidth((short)11, (short)(268*16));

		// 设置字体格式
		HSSFFont font = workbook.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		font.setFontName("仿宋_GB2312");
		font.setFontHeightInPoints((short) 12);
		// 创建格式模型
		HSSFCellStyle cs = workbook.createCellStyle();
		cs.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
		cs.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
		cs.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
		cs.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
		// 自动换行
		cs.setWrapText(true);
		// 上下居中
		cs.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		cs.setFont(font);
		// 创建数据项格式
		HSSFCellStyle cs1 = workbook.createCellStyle();
		cs1.setBorderTop(HSSFCellStyle.BORDER_THIN);
		cs1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		cs1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		cs1.setBorderRight(HSSFCellStyle.BORDER_THIN);
		cs1.setWrapText(true);
		cs1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		String[] titles = { "日期", "期号", "事发时间", "首报时间", "首报单位","地点","事件标题","类别","等级","领导现场指挥","区领导批示","报市应急办","处置中存在的问题","首报人","接电人" };
		HSSFRow dataTitleRow = sheet.createRow((short) sheetRowNum++);

		
		//获取用户选择的输出项
		for (int i = 0; i < titles.length; i++) {
			HSSFCell cell = dataTitleRow.createCell((short) i);
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(new HSSFRichTextString(titles[i]));
			cell.setCellStyle(cs);
		}
			
		// 数据模型转换:创建表格数据
		for (int i = 0; i < list.size(); i++) {
			EventExport eventexport = (EventExport) list.get(i);
			HSSFRow dataRow = sheet.createRow((short) (i+sheetRowNum));
			HSSFCell celldate = dataRow.createCell((short) 0);
			HSSFCell cellqihao = dataRow.createCell((short) 1);
			HSSFCell cellhappentime = dataRow.createCell((short) 2);
			HSSFCell cellreporttime = dataRow.createCell((short) 3);
			HSSFCell cellreportdepart = dataRow.createCell((short) 4);
			HSSFCell celladdress = dataRow.createCell((short) 5);
			HSSFCell cellevent = dataRow.createCell((short) 6);
			HSSFCell celltype = dataRow.createCell((short) 7);
			HSSFCell cellgrade = dataRow.createCell((short) 8);
			HSSFCell cellcommand = dataRow.createCell((short) 9);
			HSSFCell cell1denote = dataRow.createCell((short) 10);
			HSSFCell cell1report = dataRow.createCell((short) 11);
			HSSFCell cell1problem = dataRow.createCell((short) 12);
			// 中文编码
			celldate.setCellValue(new HSSFRichTextString(eventexport.getDate()));
			cell2.setCellValue(new HSSFRichTextString(jinzhan.getDetailcontent()));
			cellhappentime.setCellValue(new HSSFRichTextString(eventexport.getHappentime()));
			cellreporttime.setCellValue(new HSSFRichTextString(eventexport.getReporttime()));
			cellreportdepart.setCellValue(new HSSFRichTextString(eventexport.getDepartment()));
			celladdress.setCellValue(new HSSFRichTextString(eventexport.getPlace()));
			cellevent.setCellValue(new HSSFRichTextString(eventexport.getEventcontent()));
			celltype.setCellValue(new HSSFRichTextString(eventexport.getEventtype()));
			cellgrade.setCellValue(new HSSFRichTextString(eventexport.getEventlevel()));
			cellcommand.setCellValue(new HSSFRichTextString(eventexport.getLocalleader()));
			cell1denote.setCellValue(new HSSFRichTextString(eventexport.getDenote()));
			cell1report.setCellValue(new HSSFRichTextString(eventexport.getReportflag()));
				
			// 设置各个列的格式
			celldate.setCellStyle(cs1);
			cellqihao.setCellStyle(cs1);
			cellhappentime.setCellStyle(cs1);
			cellreporttime.setCellStyle(cs1);
			cellreportdepart.setCellStyle(cs1);
			celladdress.setCellStyle(cs1);
			cellevent.setCellStyle(cs1);
			celltype.setCellStyle(cs1);
			cellgrade.setCellStyle(cs1);
			cellcommand.setCellStyle(cs1);
			cell1denote.setCellStyle(cs1);
			cell1report.setCellStyle(cs1);
			cell1problem.setCellStyle(cs1);
		
		}
		//输出文件
		OutputStream out = response.getOutputStream();
		response.setCharacterEncoding("gbk");
		response.setContentType("application/x-msexcel");
		response.setHeader("Content-Disposition", "attachment;filename="
				+ ExportUtil.UniC(title) + ".xls");

		workbook.write(out);
		out.close();
	}



Java代码 复制代码
  1. /**  
  2.      * 添加标题栏的内容和设置标题格式  
  3.      *   
  4.      * @param workbook  
  5.      * @param sheet  
  6.      * @param region  
  7.      * @param text  
  8.      * @param cs  
  9.      */  
  10.     public static void fillMergedRegion(HSSFWorkbook workbook, HSSFSheet sheet,   
  11.             Region region, String text, HSSFCellStyle cs) {   
  12.         cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);   
  13.         setRegionStyle(workbook, sheet, region, cs);   
  14.         HSSFRow row;   
  15.         HSSFCell cell;   
  16.         // 设置字体格式   
  17.         HSSFFont font = workbook.createFont();   
  18.         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);   
  19.         font.setFontHeightInPoints((short18);   
  20.         // 居中显示   
  21.         cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);   
  22.         cs.setFont(font);   
  23.   
  24.         row = sheet.getRow(region.getRowFrom());   
  25.         cell = row.getCell(region.getColumnFrom());   
  26.         cell.setCellValue(new HSSFRichTextString(text));   
  27.         sheet.addMergedRegion(region);   
  28.     }  
/**
	 * 添加标题栏的内容和设置标题格式
	 * 
	 * @param workbook
	 * @param sheet
	 * @param region
	 * @param text
	 * @param cs
	 */
	public static void fillMergedRegion(HSSFWorkbook workbook, HSSFSheet sheet,
			Region region, String text, HSSFCellStyle cs) {
		cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		setRegionStyle(workbook, sheet, region, cs);
		HSSFRow row;
		HSSFCell cell;
		// 设置字体格式
		HSSFFont font = workbook.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		font.setFontHeightInPoints((short) 18);
		// 居中显示
		cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		cs.setFont(font);

		row = sheet.getRow(region.getRowFrom());
		cell = row.getCell(region.getColumnFrom());
		cell.setCellValue(new HSSFRichTextString(text));
		sheet.addMergedRegion(region);
	}



Java代码 复制代码
  1. public static void setRegionStyle(HSSFWorkbook workbook, HSSFSheet sheet,   
  2.             Region region, HSSFCellStyle cs) {   
  3.         for (int i = region.getRowFrom(); i <= region.getRowTo(); i++) {   
  4.             HSSFRow row = HSSFCellUtil.getRow(i, sheet);   
  5.             for (int j = region.getColumnFrom(); j <= region.getColumnTo(); j++) {   
  6.                 HSSFCell cell = HSSFCellUtil.getCell(row, (short) j);   
  7.                 cell.setCellStyle(cs);   
  8.             }   
  9.         }   
  10.     }  

你可能感兴趣的:(Excel,J#)