您的位置:首页 > 数据库

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

2017-11-24 09:57 363 查看
导出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
4000
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());//电话
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: