java操作excel 工具类

java操作excel

  可参考https://blog.csdn.net/xunwei0303/article/details/53213130

直接上代码:

一、java生成excel文件:

package com.excel;

public class Man {
private String name;
private int sex;
private String idCard;
private float salary;
public Man(String name, int sex, String idCard, float salary) {
super();
this.name = name;
this.sex = sex;
this.idCard = idCard;
this.salary = salary;
} public Man() {
super();
} public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
} }
package com.excel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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;
import org.apache.poi.ss.util.CellRangeAddress; public class ExcelExportUtil {
HttpServletResponse response;
// 文件名
private String fileName ;
//文件保存路径
private String fileDir;
//sheet名
private String sheetName;
//表头字体
private String titleFontType = "Arial Unicode MS";
//表头背景色
private String titleBackColor = "C1FBEE";
//表头字号
private short titleFontSize = 12;
//添加自动筛选的列 如 A:M
private String address = "";
//正文字体
private String contentFontType = "Arial Unicode MS";
//正文字号
private short contentFontSize = 12;
//Float类型数据小数位
private String floatDecimal = ".00";
//Double类型数据小数位
private String doubleDecimal = ".00";
//设置列的公式
private String colFormula[] = null; DecimalFormat floatDecimalFormat=new DecimalFormat(floatDecimal);
DecimalFormat doubleDecimalFormat=new DecimalFormat(doubleDecimal); private HSSFWorkbook workbook = null; public ExcelExportUtil(String fileDir,String sheetName){
this.fileDir = fileDir;
this.sheetName = sheetName;
workbook = new HSSFWorkbook();
} public ExcelExportUtil(HttpServletResponse response,String fileName,String sheetName){
this.response = response;
this.sheetName = sheetName;
workbook = new HSSFWorkbook();
}
/**
* 设置表头字体.
* @param titleFontType
*/
public void setTitleFontType(String titleFontType) {
this.titleFontType = titleFontType;
}
/**
* 设置表头背景色.
* @param titleBackColor 十六进制
*/
public void setTitleBackColor(String titleBackColor) {
this.titleBackColor = titleBackColor;
}
/**
* 设置表头字体大小.
* @param titleFontSize
*/
public void setTitleFontSize(short titleFontSize) {
this.titleFontSize = titleFontSize;
}
/**
* 设置表头自动筛选栏位,如A:AC.
* @param address
*/
public void setAddress(String address) {
this.address = address;
}
/**
* 设置正文字体.
* @param contentFontType
*/
public void setContentFontType(String contentFontType) {
this.contentFontType = contentFontType;
}
/**
* 设置正文字号.
* @param contentFontSize
*/
public void setContentFontSize(short contentFontSize) {
this.contentFontSize = contentFontSize;
}
/**
* 设置float类型数据小数位 默认.00
* @param doubleDecimal 如 ".00"
*/
public void setDoubleDecimal(String doubleDecimal) {
this.doubleDecimal = doubleDecimal;
}
/**
* 设置doubel类型数据小数位 默认.00
* @param floatDecimalFormat 如 ".00
*/
public void setFloatDecimalFormat(DecimalFormat floatDecimalFormat) {
this.floatDecimalFormat = floatDecimalFormat;
}
/**
* 设置列的公式
* @param colFormula 存储i-1列的公式 涉及到的行号使用@替换 如A@+B@
*/
public void setColFormula(String[] colFormula) {
this.colFormula = colFormula;
}
/**
* 写excel.
* @param titleColumn 对应bean的属性名
* @param titleName excel要导出的表名
* @param titleSize 列宽
* @param dataList 数据
* @param sheetName excel 页名
*/
public void wirteExcel(String titleColumn[],String titleName[],int titleSize[],List<?> dataList, String sheetName){
//添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
Sheet sheet = workbook.createSheet(this.sheetName);
//新建文件
OutputStream out = null;
try {
if(fileDir!=null){
//有文件路径
out = new FileOutputStream(fileDir);
}else{
//否则,直接写到输出流中
out = response.getOutputStream();
fileName = fileName+".xls";
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(fileName, "UTF-8"));
} //写入excel的表头
Row titleNameRow = workbook.getSheet(sheetName).createRow(0);
//设置样式
HSSFCellStyle titleStyle = workbook.createCellStyle();
titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, titleFontType, (short) titleFontSize);
titleStyle = (HSSFCellStyle) setColor(titleStyle, titleBackColor, (short)10); for(int i = 0;i < titleName.length;i++){
sheet.setColumnWidth(i, titleSize[i]*256); //设置宽度
Cell cell = titleNameRow.createCell(i);
cell.setCellStyle(titleStyle);
cell.setCellValue(titleName[i].toString());
} //为表头添加自动筛选
if(!"".equals(address)){
CellRangeAddress c = (CellRangeAddress) CellRangeAddress.valueOf(address);
sheet.setAutoFilter(c);
} //通过反射获取数据并写入到excel中
if(dataList!=null&&dataList.size()>0){
//设置样式
HSSFCellStyle dataStyle = workbook.createCellStyle();
titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, contentFontType, (short) contentFontSize); if(titleColumn.length>0){
for(int rowIndex = 1;rowIndex<=dataList.size();rowIndex++){
Object obj = dataList.get(rowIndex-1); //获得该对象
Class clsss = obj.getClass(); //获得该对对象的class实例
Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
for(int columnIndex = 0;columnIndex<titleColumn.length;columnIndex++){
String title = titleColumn[columnIndex].toString().trim();
if(!"".equals(title)){ //字段不为空
//使首字母大写
String UTitle = Character.toUpperCase(title.charAt(0))+ title.substring(1, title.length()); // 使其首字母大写;
String methodName = "get"+UTitle; // 设置要执行的方法
Method method = clsss.getDeclaredMethod(methodName); //获取返回类型
String returnType = method.getReturnType().getName(); String data = method.invoke(obj)==null?"":method.invoke(obj).toString();
Cell cell = dataRow.createCell(columnIndex);
if(data!=null&&!"".equals(data)){
if("int".equals(returnType)){
cell.setCellValue(Integer.parseInt(data));
}else if("long".equals(returnType)){
cell.setCellValue(Long.parseLong(data));
}else if("float".equals(returnType)){
cell.setCellValue(floatDecimalFormat.format(Float.parseFloat(data)));
}else if("double".equals(returnType)){
cell.setCellValue(doubleDecimalFormat.format(Double.parseDouble(data)));
}else{
cell.setCellValue(data);
}
}
}else{ //字段为空 检查该列是否是公式
if(colFormula!=null){
String sixBuf = colFormula[columnIndex].replace("@", (rowIndex+1)+"");
Cell cell = dataRow.createCell(columnIndex);
cell.setCellFormula(sixBuf.toString());
}
}
}
} }
} workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 将16进制的颜色代码写入样式中来设置颜色
* @param style 保证style统一
* @param color 颜色:66FFDD
* @param index 索引 8-64 使用时不可重复
* @return
*/
public CellStyle setColor(CellStyle style,String color,short index){
if(color!=""&&color!=null){
//转为RGB码
int r = Integer.parseInt((color.substring(0,2)),16); //转为16进制
int g = Integer.parseInt((color.substring(2,4)),16);
int b = Integer.parseInt((color.substring(4,6)),16);
//自定义cell颜色
HSSFPalette palette = workbook.getCustomPalette();
palette.setColorAtIndex((short)index, (byte) r, (byte) g, (byte) b); //style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(index);
}
return style;
} /**
* 设置字体并加外边框
* @param style 样式
* @param style 字体名
* @param style 大小
* @return
*/
public CellStyle setFontAndBorder(CellStyle style,String fontName,short size){
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints(size);
font.setFontName(fontName);
font.setBold(true);
style.setFont(font);
//style.setBorderBottom(CellStyle.BORDER_THIN); //下边框
//style.setBorderLeft(CellStyle.BORDER_THIN);//左边框
//style.setBorderTop(CellStyle.BORDER_THIN);//上边框
//style.setBorderRight(CellStyle.BORDER_THIN);//右边框
return style;
}
/**
* 删除文件
* @param fileDir
* @return
*/
public boolean deleteExcel(){
boolean flag = false;
File file = new File(this.fileDir);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
file.delete();
flag = true;
}
}
return flag;
}
/**
* 删除文件
* @param fileDir
* @return
*/
public boolean deleteExcel(String path){
boolean flag = false;
File file = new File(path);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
file.delete();
flag = true;
}
}
return flag;
}
}
package com.excel;

import java.util.ArrayList;
import java.util.List; public class ExcelTest { public static void main(String[] args) {
//1.获取数据[数据库]
List<Man> dataList = new ArrayList();
Man man1 = new Man("张三",20,"男",(float)10000.8);
Man man2 = new Man("李四",21,"男",(float)11000.8);
Man man3 = new Man("王五",22,"女",(float)1200.8);
Man man4 = new Man("赵六",23,"男",(float)13000.8);
Man man5 = new Man("田七",24,"男",(float)14000.8);
Man man6 = new Man();
man6.setName("老八");
dataList.add(man1);dataList.add(man2);dataList.add(man3);dataList.add(man4);dataList.add(man5);
dataList.add(man6);
//2.分页,每页显示2行
int pageSize = 2;// 定义每页数据数量
int listCount = dataList.size();
//总数量除以每页显示条数等于页数
int exportTimes = listCount % pageSize > 0 ? listCount / pageSize + 1 : listCount / pageSize; //3.通用的设置(标题、公式等)
String titleColumn[] = {"name","sex","idCard","salary",""};
String titleName[] = {"姓名","性别","身份证号","月薪","年薪"};
int titleSize[] = {13,13,13,13,13};
//其他设置 set方法可全不调用
String colFormula[] = new String[5];
colFormula[4] = "D@*12"; //设置第5列的公式
//工具对象
ExcelExportUtil pee = new ExcelExportUtil("E:/test.xls","sheet"); //4.循环获取产生每页数据
for (int i = 0; i < exportTimes; i++) { pee.setColFormula(colFormula);
pee.setAddress("A:D"); //自动筛选 List<Man> subList = dataList.subList(i*pageSize, ((i+1)*pageSize));
pee.wirteExcel(titleColumn, titleName, titleSize, subList, "sheet" + (i + 1));
} System.out.println("excel生成完毕!"); } }

二、java读取excel文件:

package com.excel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
/**
* Excel数据封装对象
* @author kongzhimin
*
*/
public class ExcelEntity {
/**
* EXCEL表头字段
*/
private String[] heard;
/**
* EXCEL内容封装
*/
private JSONArray context;
public String[] getHeard() {
return heard;
}
public void setHeard(String[] heard) {
this.heard = heard;
}
public JSONArray getContext() {
return context;
}
public void setContext(JSONArray context) {
this.context = context;
}
@Override
public String toString() {
return JSON.toJSONString(this);
}
}
package com.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map; import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.alibaba.fastjson.JSONArray; import net.sf.json.JSONObject; /**
* excel工具类
* @author weijiaquan
*
*/
public class ExcelUtil { private static final Logger log = Logger.getLogger(ExcelUtil.class); /**
* EXCEL读取的数据表对象
*/
private static Sheet sheet;
/**
* 行数
*/
private static Integer rowNum;
/**
* 列数
*/
private static Integer colNum;
/**
* 数据表表头位置
*/
private static Integer headNum;
/**
* 数据表表头字段与bean字段映射
*/
private Map<String,String> headMap;
/**
* excel 内容
*/
private static JSONArray excelContent = new JSONArray();
/**
* excel 标题
*/
private static String[] excelTitle = new String[0];
/**
* 表头字段列表
*/
private static String[] heads = {"dateTime","hours","publicNum","mediaName","mediaSource","sums","dNum","iNum"}; /**
* workbook
*/
private static Workbook workbook; /**
* 解析excel
* @param file
* @return
* @throws IOException
*/
public static void readerExcel(File file) throws IOException {
// 1.检查文件
checkFile(file);
// 2.获得Workbook工作薄对象
workbook = getWorkBook(file);
if (workbook != null) {
System.out.println("excel总页数sheetNum= "+ workbook.getNumberOfSheets());
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
// 3.初始化init
System.out.println("第" + sheetNum + "页");
init(sheetNum); // 4.读取Excel
// 4.1 获取title[不用分页读取]--title理应一样 // 4.2获取内容[取所有页的内容]
JSONArray currentContent = readExcelContent();
System.out.println("currentContent" + sheetNum + "--" + currentContent.size());
for (Object object : currentContent) {
excelContent.add(object);
}
if (sheet == null) {
continue;
}
}
}
} /**
* 获取每个单元格的值
* @param cell
* @return
*/
public static String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}
// 判断数据的类型
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: // 数字
cellValue = stringDateProcess(cell);
break;
case Cell.CELL_TYPE_STRING: // 字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: // 公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: // 空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
} /**
* 时间格式处理
* @return
* @author weijiaquan
*/
public static String stringDateProcess(Cell cell){
String result = new String();
if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
SimpleDateFormat sdf = null;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
sdf = new SimpleDateFormat("HH:mm");
} else {// 日期
sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
}
Date date = cell.getDateCellValue();
result = sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58) {
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil
.getJavaDate(value);
result = sdf.format(date);
} else {
double value = cell.getNumericCellValue();
CellStyle style = cell.getCellStyle();
DecimalFormat format = new DecimalFormat("#,#######");
String temp = style.getDataFormatString();
// 单元格设置成常规
if (temp.equals("General")) {
format.applyPattern("#");
}
result = format.format(value);
} return result;
} /**
* 检查文件
* @param file
* @throws IOException
*/
public static void checkFile(File file) throws IOException{
//判断文件是否存在
if(null == file){
log.error("文件不存在!");
}
//获得文件名
String fileName = file.getName();
//判断文件是否是excel文件
if(!fileName.endsWith("xls") && !fileName.endsWith("xlsx")){
log.error(fileName + "不是excel文件");
}
}
/**
* 获得Workbook工作薄对象
* @param file
* @return
*/
public static Workbook getWorkBook(File file) {
//获得文件名
String fileName = file.getName();
//创建Workbook工作薄对象,表示整个excel
Workbook workbook = null;
try {
//获取excel文件的io流
InputStream is = new FileInputStream(file);
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
if(fileName.endsWith("xls")){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith("xlsx")){
//2007 及2007以上
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
log.error(e.getMessage());
}
return workbook;
} /**
* 读取Excel表格表头的内容
* @param InputStream
* @return String 表头内容的数组
*/
private static String[] readExcelTitle() {
Row row = sheet.getRow(headNum);
System.out.println("colNum:" + colNum);
String[] title = new String[colNum];
for (int i = 0; i < colNum; i++) {
title[i] = getCellValue(row.getCell(i));
}
return title;
}
/**
* reader初始化方法
* @throws IOException
*/
private static void init(Integer sheetNum) throws IOException {
sheet = workbook.getSheetAt(sheetNum);
rowNum = sheet.getLastRowNum();
headNum = 0;
colNum = sheet.getRow(0).getPhysicalNumberOfCells();
heads = readExcelTitle();
} /**
* 解析EXCEL文件成为Entity对象
* @return ExcelEntity Excel解析实体对象
* @throws IOException
*/
public static ExcelEntity parseExcelToEntity(File file) throws IOException {
//1.解析excel
readerExcel(file);
//2.封装对象
ExcelEntity entity = new ExcelEntity();
entity.setHeard(readExcelTitle());
entity.setContext(excelContent);
return entity;
} /**
* 读取Excel数据内容
* @param InputStream
* @return JSONArray 包含单元格数据内容的对象
*/
private static JSONArray readExcelContent() {
JSONArray array = new JSONArray();
for (int i = headNum+1; i <= rowNum; i++) {
array.add(parseRowToObject(i));
}
return array;
} /**
* 数据表行转化JSONObject
* @param rowNum
* @return
*/
private static JSONObject parseRowToObject(Integer rowNum) {
JSONObject object = new JSONObject();
Row row = sheet.getRow(rowNum);
for (int i = 0; i < colNum; i++) {
object.put(heads[i], getCellValue(row.getCell(i)));
}
return object;
} public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\weijiaquan\\excel\\201807091922.xls"); ExcelEntity excelEntity = parseExcelToEntity(file);
JSONArray context = excelEntity.getContext();
for (int i = 0; i < context.size(); i++) {
com.alibaba.fastjson.JSONObject jsonObject = context.getJSONObject(i);
String sql = "INSERT INTO T(groupId,lenderId,lenderUrlId,nPriority,nStatus,createBy,createdDate,updateBy,updatedDate) VALUES (17101,%s,%s,%s,0,'system',now(),'system',now());";
String format = String.format(sql, jsonObject.get("lenderid"), jsonObject.get("urlid"), jsonObject.get("order"));
System.out.println(format);
//System.out.println(jsonObject);
}
}
}

  

上一篇:Java解析Excel工具类(兼容xls和xlsx)


下一篇:JAVA 操作Excel工具类