Jxl解析Excel表格数据

/**
* @file ExcelUtils.java
*
* @brief ExcelUtils.java相关函数
*
*
* @author
* - Dec 28, 2011 xxxx *
* @par 版权信息:
* Copyright(C) 2011-2011 鑫万佳
*/
package com.xwj.reflact;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.log4j.Logger;

import com.xwj.bean.code.HeXinTradeCode;
import com.xwj.bean.code.TradeCode;
import com.xwj.bean.code.TradeCodeRelationShip;

/**
* 相关函数 处理Excel的工具类
*
* @author Dec 28, 2011 xxxx 创建初始版本
*
* @version V0.1
*
*/
public class ExcelUtils {

private static Logger log = Logger.getLogger(ExcelUtils.class);

/**
*
* @方法功能描述:导出Excel表格的工具类
*
* @param res
* HttpServletResponse 相应对象
* @param filename
* 导出的Excel文件名称
* @param sheetName
* Excel sheet 表单名称
* @param tableHeadName
* Excel sheet 表头名称
* @param titlesList
* 导出的Excel表格的表头名称
* @param contentList
* 要写入表格的数据集合
* @author: xxxx
* @CreateDate: Dec 28, 2011
*/
public static void exportExcel_2(HttpServletResponse res, String filename,
String sheetName, String tableHeadName, List titlesList,
List contentList) {
try {
res.reset();
res.setContentType("application/vnd.ms-excel");
res.addHeader("Content-disposition", "attachment; filename=\""
+ new String(filename.getBytes(), "ISO8859-1") + "\""
+ ".xls");
// 获取工作表
WritableWorkbook book = Workbook.createWorkbook(res
.getOutputStream());
WritableSheet sheet = book.createSheet("sheet_1", 0);

// 添加表头
Label labelHead = new Label(0, 0, tableHeadName);
sheet.addCell(labelHead);

// 生成Excel表头数据
for (int i = 0; i < titlesList.size(); i++) {
// Label(col, row, content)
Label label = new Label(i, 1, titlesList.get(i).toString());
sheet.addCell(label);
}

// 生成表格数据
int index = 2;// 行数
// int row = 1;
int col = 0;
int totalCol = titlesList.size();// 获取总列数
for (int i = 0; i < contentList.size(); i++, col++) {
if (col == totalCol) {
index++;
col = 0;
}
Label label = new Label(col, index, contentList.get(i)
.toString());
sheet.addCell(label);
}

book.write();// 写出Excel表格
book.close();

res.getOutputStream().flush();
res.getOutputStream().close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}

/**
*
*@方法功能描述:根据查询的list返回Excel表格的方法
*
*@param res
* HttpServletResponse 相应对象
*@param filename
* 导出的 Excel 文件名称
*@param sheetName
* Excel sheet 表单名称
*@param tableHeadName
* Excel sheet 表头名称
*@param titlesList
* 导出的 Excel 表格的表头名称
*@param objFieldList
* 要显示 list 里面所装的对象的字段列表集合
*@param contentList
* 要写入表格的数据集合
*@author: xxxx
*@CreateDate: Dec 28, 2011
*/
public static void exportExcel(HttpServletResponse response, String filename,
String sheetName, String tableHeadName, List<Object> titlesList,
List<String>objFieldList, List<?> contentList) {
try {
response.reset();
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-disposition", "attachment; filename=\""
+ new String(filename.getBytes(), "ISO8859-1") + "\"" + ".xls");

// 获取工作表
WritableWorkbook book = Workbook.createWorkbook(response.getOutputStream());
WritableSheet sheet = book.createSheet(sheetName, 0);

// 添加表头
Label labelHead = new Label(0, 0, tableHeadName);
sheet.addCell(labelHead);
sheet.mergeCells(0, 0, titlesList.size()-1, 0);//合并表头信息
WritableCellFormat wc = new WritableCellFormat();
// 设置居中
wc.setAlignment(Alignment.CENTRE);
WritableFont wfont = new WritableFont( WritableFont.createFont("隶书"), 20);
WritableCellFormat font = new WritableCellFormat(wfont);
wc.setFont(wfont);
labelHead.setCellFormat(wc);

// 生成Excel表头数据
for (int i = 0; i < titlesList.size(); i++) {
// Label(col, row, content)
Label label = new Label(i, 1, titlesList.get(i).toString());
sheet.addCell(label);
}

Object obj = null;
Class objClazz = null;
if (contentList != null && contentList.size() != 0) {
obj = contentList.get(0);//获取list里面放置的对象
}
if (obj != null) {
objClazz = obj.getClass();
}
Field[] filds = objClazz.getDeclaredFields();//获取对象的所有字段
int index = 2;// 行数
int col = 0;//列数
int totalCol = titlesList.size();// 获取总列数
// 生成表格数据
for (int i = 0,len = contentList.size(); i < len; i++) {
Object objArg = contentList.get(i);//获取list里面放置的对象
Object content = null;//objArg 字段值
boolean fg = false;
for (Field fd : filds) {//循环取出每个字段
String fildName = fd.getName();
for (String objAttribute : objFieldList) {
if (fildName != null && objAttribute != null && objAttribute.equals(fildName)) {
boolean flag = fd.isAccessible();
fd.setAccessible(true);
content = fd.get(objArg);//获取字段的相关属性值
fd.setAccessible(flag);
fg = true;
break;
}
}
if (fg) {//当为TRUE的时候才可以把值写入Excel表格
if (col == totalCol) {//当前的列数等于表格的总列数时 即一条数据就结束
index++;//行数转为下一行
col = 0;//列数又从0开始
}
fg = false;
Label label = new Label(col++, index, content.toString());
sheet.addCell(label);
}
}
}

book.write();// 写出Excel表格
book.close();
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (UnsupportedEncodingException e) {
log.error(" 导出表格 ExcelUtils 的方法 exportExcel 出现异常……………………………");
e.printStackTrace();
} catch (IOException e) {
log.error(" 导出表格 ExcelUtils 的方法 exportExcel 出现异常……………………………");
e.printStackTrace();
} catch (RowsExceededException e) {
log.error(" 导出表格 ExcelUtils 的方法 exportExcel 出现异常……………………………");
e.printStackTrace();
} catch (WriteException e) {
log.error(" 导出表格 ExcelUtils 的方法 exportExcel 出现异常……………………………");
e.printStackTrace();
} catch (IllegalAccessException e) {
log.error(" 导出表格 ExcelUtils 的方法 exportExcel 出现异常……………………………");
e.printStackTrace();
}
}

/**
*
* @方法功能描述:实现Excel表格的解析
*
* @param copyUrlFile
* Excel 表格所在的路径
* @param sheetName
* Excel 表格中的sheet名子
* @param clazz
* 表单所对应的对象
* @param fildsNameList
* 表格的每一列所对应的Java对象的属性名称,每一个属性名称必须和对象的属性名一样
* @param isHaveTitle
* 表格是否有一个合并的Title
* </li>true 表示有</li>
* </li>false 表示没有</li>
*
* @param isHaveHead 表格是否有一个每一列的列头 这个应该是有的
* </li>true 表示有</li>
* </li>false 表示没有</li>
* @return
* @author: xxxx
* @CreateDate: Dec 29, 2011
*/
public static List parseExcel(String copyUrlFile, String sheetName, Class clazz, List<String>fildsNameList, boolean isHaveTitle, boolean isHaveHead) {

Workbook rwb = null;
Map<String, String> map = null;
List<String> valueList = null;//用来保存Excel表格的每一行中每一个单元格的内容
List listObj = new ArrayList();//保存每一行的行对象
try {
rwb = Workbook.getWorkbook(new File(copyUrlFile));
Sheet sheet = rwb.getSheet(sheetName);//根据sheetName表单的名字获取表单
int rows = sheet.getRows();//总行数
int columns = sheet.getColumns();//总列数
Field[] fields = clazz.getDeclaredFields();
for (int r = 0; r < rows; r++) {//行循环
if (isHaveTitle && isHaveHead) {
if (r == 1 || r == 0) {//排除合并的表头 和 每一列的列头
continue;
}
}
if (!isHaveTitle) {//如果没有合并的表头 排除每一列的列头
if (r == 0) {
continue;
}
}
map = new HashMap<String, String>();
valueList = new ArrayList<String>();
for (int c = 0; c < columns; c++) {//列循环
Cell cell = sheet.getCell(c,r);
String contents = cell.getContents();

// TODO 对输入的数据进行判断验证是否合法
// for (String fdName : fildsNameList) {
// System.out.println("fdName <===================> " + fdName);
// for (Field fd : fields) {
// if (fd.getName().equals(fdName)) {
// map.put(fdName, contents);
// break;
// }
// }
// }

valueList.add(contents);//把一行的每一列的值添加到valueList里面
if (c == (columns - 1)) {//当一行解析结束的时候就可以获取一个对象
for (int i = 0; i < fildsNameList.size(); i++) {
//key 和 value 应该是一一对应的
map.put(fildsNameList.get(i), valueList.get(i));
}
Object bean = clazz.newInstance();
Object objBean = copyMapToBean(map, bean);
listObj.add(objBean);
}
}
}
return listObj;
} catch (BiffException e) {
log.error(" 导出表格 ExcelUtils 的方法 parseExcel 出现异常……………………………");
e.printStackTrace();
} catch (IOException e) {
log.error(" 导出表格 ExcelUtils 的方法 parseExcel 出现异常……………………………");
e.printStackTrace();
} catch (InstantiationException e) {
log.error(" 导出表格 ExcelUtils 的方法 parseExcel 出现异常……………………………");
e.printStackTrace();
} catch (IllegalAccessException e) {
log.error(" 导出表格 ExcelUtils 的方法 parseExcel 出现异常……………………………");
e.printStackTrace();
}
return null;
}

/**
*
* @方法功能描述:
* <li>将前台客户输入的form表单的内容封装到map里面</li>
* <li>注意map里面的 key 必须和bean里面的属性值一一对应</li>
* <li>也就是前台 from 的input标签的name要和bean对应</li>
*
* @param map
* 对应前的from表单输入的数据
* @param bean
* 要存库的数据库对象
* @param dateFormat
* <li>如果bean对象里面有java.utils.Date 类型需要将map里面的String转为date类型</li>
* <li>dateFormat 为指定的格式 默认为 'yyyyMMdd' </li>
* @return Object
* @author: xxxx
* @CreateDate: Dec 22, 2011
*/
public static Object copyMapToBean(Map<String, String> map, Object bean) {

Class clazz = bean.getClass();// 获取bean对象的class属性
Field[] fields = clazz.getDeclaredFields();
Object argsObj = null;// set方法执行的参数
for (Field fd : fields) {
try {
String fdType = fd.getType().toString();// 获取bean对象的字段属性

String key = fd.getName();// 获取字段名称作为map的键
String value = map.get(key);// 获取map中的值

if (value == null) {// 当value为null的时候说明该字段为非必填字段 循环继续执行
continue;// 慎重应用该关键字
}

// 此处要对fd的数据类型进行判断
if (fdType != null && fdType.equals("int")) {// int
argsObj = new Integer(value).intValue();
}
if (fdType != null && fdType.equals("class java.lang.Integer")) {// Integer
argsObj = new Integer(value);
}

if (fdType != null && fdType.equals("double")) {// double
argsObj = new Double(value).doubleValue();
}
if (fdType != null && fdType.equals("class java.lang.Double")) {// Double
argsObj = new Double(value);
}

if (fdType != null && fdType.equals("float")) {// float
argsObj = new Float(value).floatValue();
}
if (fdType != null && fdType.equals("class java.lang.Float")) {// Double
argsObj = new Float(value);
}

if (fdType != null && fdType.equals("long")) {// long
argsObj = new Long(value).longValue();
}
if (fdType != null && fdType.equals("class java.lang.Long")) {// Long
argsObj = new Long(value);
}

if (fdType != null && fdType.equals("short")) {// short
argsObj = new Short(value).shortValue();
}
if (fdType != null && fdType.equals("class java.lang.Short")) {// Short
argsObj = new Short(value);
}

// TODO 字符型

// TODO byte型

if (fdType != null && fdType.equals("class java.math.BigDecimal")) {// BigDecimal
argsObj = new BigDecimal(value);
}
/*
if (fdType != null && fdType.equals("class java.util.Date")) {// Date
if (dateFormat == null) {
dateFormat = "yyyyMMdd";
}
System.out.println("value-----eye---->" + value);
//argsObj = DateUtils.stringToDate(dateFormat, value);//转化日期对象
}*/

if (fdType != null && fdType.equals("class java.lang.String")) {// String 类型
argsObj = value;
}
boolean flag = fd.isAccessible();
fd.setAccessible(true);
// 执行bean对象的set方法
fd.set(bean, argsObj);
fd.setAccessible(flag);
} catch (IllegalArgumentException e) {
e.printStackTrace();
System.out.println("BeanCopyUtils----->copyMapToBean 方法执行异常");
} catch (IllegalAccessException e) {
e.printStackTrace();
System.out.println("BeanCopyUtils----->copyMapToBean 方法执行异常");
}
}
return bean;
}

//测试方法
public static void main(String[] args) {
String sheetName = "Sheet1";
String copyUrlFile_1 = "./src/test.xls";
//调用解析的方法实现解析
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值