将数据库中的数据导出为Excel文件

导出excel文件的简单小例子(仅供大家参考),建议前台页面用链接跳转导出,浏览器可以识别并弹出下载提示框,不能用ajax

其他简单代码省略,核心代码如下:

        实体类:Person.java

public class Person{
	//用户名
	private String username;
	//电话
	private String phone;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
}

        需要用到自定义的工具类:ExcelUtil.java

package com.deppon.bi.module.report.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

public class ExcelUtil {
	/**
	 * 创建Excel列
	 * @param hs
	 * @param row
	 * @param cellStyle
	 */
	public static void createColumn(Sheet hs, Row row, CellStyle cellStyle,
			int column, int width, String columnName) {
		hs.setColumnWidth(column, width);// 设置列宽
		Cell cell = row.createCell(column); // 创建单元格
		cell.setCellType(Cell.CELL_TYPE_STRING); // 定义单元格为字符串类型
		cell.setCellStyle(cellStyle);// 设置单元格样式
		cell.setCellValue(columnName);// 设置单元格值
	}
	/**
	 * 给Excel单元格填充值
	 * @param idx
	 * @param row
	 * @param cellStyle
	 */
	public static void setCellValue(int idx, Row row, CellStyle cellStyle,
			String value) {
		Cell cell = row.createCell(idx);
		cell.setCellType(Cell.CELL_TYPE_STRING);
		cell.setCellStyle(cellStyle);
		cell.setCellValue(value);
	}
	
	public static void setCellValue2(int idx,Row row,CellStyle cellStyle,double value){
		Cell cell = row.createCell(idx);
		cell.setCellType(Cell.CELL_TYPE_STRING);
		cell.setCellStyle(cellStyle);
		cell.setCellValue(value);
	}
	
	/**
	 * 将小数转为百分数
	 */
	public static String decimalToPercent(String str){
		double temp = Double.valueOf(str).doubleValue();
		BigDecimal b = new BigDecimal(temp*100); 
		double f1 = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
		String result = Double.toString(f1);
		result = result + "%";
		return result;
	}
	
	/**
	 * 将String转double转String,四舍五入并保留两位有效数字
	 * @return
	 */
	public static String stringToDouble(String str){
		double d = Double.parseDouble(str);
		DecimalFormat df = new DecimalFormat("0.00");
		String s = df.format(d);
		return s;
	}	
	/*
	public static String stringToDouble(String str){
		public static String stringToDouble(String str){
		double d = Double.parseDouble(str);
		BigDecimal b = new BigDecimal(d);
		double f1 = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
		String result = Double.toString(f1);
		return result;
	}	 
	*/
}
        Action层:ExportExcelDemoAction.java

public class Demo {
	/**
	 * 导出方法
	 * @return
	 * @throws IOException 
	 */
	public String exportProfitPart(){
		Person person = new Person(); //实体类
		HttpServletResponse response = ServletActionContext.getResponse();
		String fileName = null;
		try {
			fileName = new String("员工信息表".getBytes(),"iso-8859-1") + ".xlsx";
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		
		// 第一步,创建一个webbook,对应一个Excel文件
                XSSFWorkbook wb = new XSSFWorkbook(); 
        
                try{
        	    //导出具体实现方法
        	    manageExcel(wb,person);
                }catch(Exception e){
        	    e.printStackTrace();
                }
                // excel保存路径
     	        OutputStream os = null;
                try{
        	        response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment; filename="
					+ fileName);
			response.setBufferSize(2048);
			os = response.getOutputStream();
			// 将excel写入到输出流
			wb.write(os);
                }catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
				    os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}      
                return null;
	}
	
	/**
	 * 导出具体实现方法
	 * 创建excel对象
	*/
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void manageExcel(XSSFWorkbook wb,Person person){
		Sheet hs = wb.createSheet();// 创建一个sheet
		Row row = null;//定义行
		CellStyle cellStyle = null;// 定义单元格样式
		CellStyle cellStyle1 = null;// 定义单元格样式
		Font font = null;// 定义字体
		// 布局
		cellStyle = wb.createCellStyle();// 创建单元格样式
		cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直
		cellStyle.setAlignment(CellStyle.ALIGN_CENTER);// 水平
		// 布局
		cellStyle1 = wb.createCellStyle();// 创建单元格样式
		font = wb.createFont();
		font.setFontHeightInPoints((short)12); // 字体大小
		cellStyle1.setFont(font);
		cellStyle1.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直
		cellStyle1.setAlignment(CellStyle.ALIGN_CENTER);// 水平
		
		// 第一行
		row = hs.createRow(0);// 在索引0的位置创建行
		int width = 2500;
		ExcelUtil.createColumn(hs, row, cellStyle, 0, width, "序号");// 第一列序号
		ExcelUtil.createColumn(hs, row, cellStyle, 1, width, "姓名");
		ExcelUtil.createColumn(hs, row, cellStyle, 2, width, "电话");
		// 查询导出数据的总数
		int allNum = managePersonService.querymanagePersonByConditionCount(condition); //(根据自己项目情况来填写,condition为查询条件)
		//根据条件查询满足的数据
		List<Person> personList = new ArrayList();
		personList = managePersonService.querymanagePersonByConditionExport(condition);//(根据自己项目情况来填写,condition为查询条件)
		
		int k=1;
		// 按次数将数据写入文件 
		for(int i=0;i<allNum;i++){  //循环行
			person = personList.get(i);
			row = hs.createRow(k++);//第k行
			int f=0;
			//循环列:往单元格中放数据
			ExcelUtil.setCellValue(f++, row, cellStyle, Integer.toString((i+1)));//序号
			ExcelUtil.setCellValue(f++, row, cellStyle, person.getUsername());// 姓名
			ExcelUtil.setCellValue(f++, row, cellStyle, person.getPhone());//电话
		}
	}
}


  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值