Java读写Excel

 package com.cplatform.coperator.mcissdrreport.util;

 
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 
public class Excel {
 
private static String STYLE_CENTER = "center";
 
private static String SYLE_RIGHT = "right";
 
private static String SYTLE_LEFT = "left";
 
private short defaultCellNum = 0;
 
private short defaultRowNum = 0;
 
private final short defaultTitleRowNum = 1;
 
private String fileName;
 
private String sheetName = "sheet1";
 
private int shortCellNum = 0;
 
private HSSFWorkbook wb = new HSSFWorkbook();
 
/**
* 默认构造函数
*/
public Excel() {
}
 
/**
* 构造函数 设置
* @param fileName
*            带绝对路径的excel文件名
*/
public Excel(String fileName) {
this.setFileName(fileName);
}
 
/**
* 构造函数:设置新工作区
* @param sheetName
*            sheetName
* @param rowNum
*            rowNum
* @param cellNum
*            cellNum
*/
public Excel(String sheetName, String rowNum, String cellNum) {
this.sheetName = sheetName;
this.defaultRowNum = Short.parseShort(rowNum);
this.defaultCellNum = Short.parseShort(cellNum);
}
 
/**
* 根据sql语句的查询结果生成记录行
* @param sheet
*            工作区对象
* @param sql
*            sql语句
* @param conn
*            数据库联接
* @return HSSFSheet
*/
public HSSFSheet createRows(HSSFSheet sheet, String sql, Connection conn, String[] title) {
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
ResultSetMetaData rsMetaData = rs.getMetaData();
String fieldName = "";
String fieldValue = "";
int colCou = rsMetaData.getColumnCount();
String fieldArr[] = new String[colCou];
for (int i = 0; i < colCou; i++) {
fieldName = rsMetaData.getColumnName(i + 1);
if (StringUtils.isBlank(fieldName)) {
fieldName = "undefined";
}
fieldArr[i] = fieldName;
}
int j = 1;
createTitleRow(sheet, title); // 创建第一行(字段名)
while (rs.next()) {
HSSFRow row = sheet.createRow(defaultRowNum + (j++));
for (int i = 0, n = fieldArr.length; i < n; i++) {
HSSFCell cell = row.createCell((short) (defaultCellNum + i));
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
fieldValue = rs.getString(fieldArr[i]) == null ? "" : (rs.getString(fieldArr[i]));
cell.setCellValue(fieldValue);
}
}
rs.close();
pstmt.close();
}
catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
 
return sheet;
 
}
 
/**
* @return 返回一个sheet对象
*/
private HSSFSheet createSheet() {
return wb.createSheet(sheetName);
}
 
/**
* 建立一个新的带标题的空表
* @param sql
*            sql语句
* @param conn
*            数据库连接
* @return HSSFWorkbook
*/
public HSSFWorkbook createTitleBook(String sql, Connection conn) {
HSSFSheet sheet = createSheet();
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
List<String> aList = new ArrayList<String>();
while (rs.next()) {
if (!rs.getString("ENAME").equals("ZTM") && !rs.getString("ENAME").equals("BMM") && !rs.getString("ENAME").equals("GUID")
       && !rs.getString("ENAME").equals("CREATE_TIME") && !rs.getString("ENAME").equals("UPDATE_TIME")
       && !"1".equals(rs.getString("IS_BINARY"))) {
aList.add(rs.getString("ENAME"));
}
}
String field[] = new String[aList.size()];
for (int k = 0; k < aList.size(); k++) {
field[k] = aList.get(k);
}
 
HSSFRow titleRow = createTitleRow(sheet, field);
rs.close();
pstmt.close();
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
 
return wb;
}
 
/**
* 建立一个标题行
* @param sheet
*            HSSFSheet
* @param title
*            标题数组
* @return HSSFRow
*/
public HSSFRow createTitleRow(HSSFSheet sheet, String[] title) {
// 创建一个新的行 行号从0开始
HSSFRow row = sheet.createRow(defaultRowNum);
 
// 设置单元格属性
 
for (int i = 0, n = title.length; i < n; i++) {
if (title[i].equals("none")) {
continue;
}
HSSFCell cell = row.createCell((short) (defaultCellNum + i));
setCellProperty(cell, HSSFCell.CELL_TYPE_STRING, Excel.SYTLE_LEFT);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(title[i]);
}
 
return row;
}
 
/**
* 建立一个新的工作簿
* @param sql
*            sql语句
* @param conn
*            数据库链接
* @return HSSFWorkbook
*/
public HSSFWorkbook createWorkBook(String sql, Connection conn, String[] fieldArr) {
HSSFSheet sheet = createSheet();
sheet = createRows(sheet, sql, conn, fieldArr);
return wb;
}
 
/**
* 本方法的是返回excel中的数值列表
* @param pIs
*            输入流
* @return arraylist 数值,每一行为一Hashtable当中存放了每一个单元格的值
* @throws Exception
*             Exception
*/
public List<HashMap<String, String>> getExcelData(InputStream pIs) throws Exception {
List<HashMap<String, String>> al = new ArrayList<HashMap<String, String>>();
HSSFWorkbook wb;
if (pIs == null) {
wb = parserXls();
} else {
wb = parserXls(pIs);
}
HSSFSheet sheet = wb.getSheetAt(0);
/*
* 取得字段列表
*/
ArrayList<String> title = new ArrayList<String>();
 
int lastrow = sheet.getLastRowNum() + 1;
for (int i = 0; i < lastrow; i++) {
HSSFRow row = sheet.getRow(i);
 
int lastcell = row.getLastCellNum();
 
if (this.shortCellNum < lastcell) {
this.shortCellNum = lastcell;
}
int k = 0;
HashMap<String, String> mapReturn = new HashMap<String, String>();
 
for (int j = 0; j < lastcell; j++) {
HSSFCell cell = row.getCell((short) j);
if (i == 0) {
title.add(cell.getStringCellValue().toUpperCase()); // 这样字段都是大写
} else {
 
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
mapReturn.put(title.get(j), cell.getStringCellValue());
break;
case HSSFCell.CELL_TYPE_NUMERIC:
double tem = cell.getNumericCellValue();
String s = Long.toString(new Double(tem).longValue());
mapReturn.put(title.get(j), s + "");
 
break;
case HSSFCell.CELL_TYPE_FORMULA:
mapReturn.put(title.get(j), cell.getCellFormula() + "");
break;
default:
mapReturn.put(title.get(j), "");
k++;
break;
}
} else {
mapReturn.put(title.get(j), "");
k++;
}
}
}
if (i > 0 && k != lastcell)
al.add(mapReturn);
}
 
return al;
}
 
/**
* @return Returns the fileName.
*/
private String getFileName() {
return fileName;
}
 
public int getShortCellNum() {
return shortCellNum;
}
 
/**
* 本方法的是读该excel文件并写到处理对象中去
* @return
* @throws Exception
* @author wunaigang(2005-7-14)
*/
private HSSFWorkbook parserXls() throws Exception {
String fileName = this.getFileName();
InputStream fileOut = null;
HSSFWorkbook wb = null;
 
if (fileName == null || "".equals(fileName)) {
throw new Exception("excel file is empty");
} else {
fileOut = new FileInputStream(fileName);
wb = new HSSFWorkbook(fileOut);
}
return wb;
}
 
/**
* 本方法的是读该excel文件并写到处理对象中去
* @param pIs
*            输入流
* @return HSSFWorkbook
* @throws Exception
*             Exception
*/
private HSSFWorkbook parserXls(InputStream pIs) throws Exception {
 
if (pIs == null) {
throw new Exception("no excel InputStream inputed");
} else {
wb = new HSSFWorkbook(pIs);
}
return wb;
}
 
/**
* 设置单元格属性
* @param cell
*            列
* @param type
*            列类型
* @param align
*            align
*/
public void setCellProperty(HSSFCell cell, int type, String align) {
cell.setCellType(type);
HSSFCellStyle style = wb.createCellStyle();
if (Excel.STYLE_CENTER.equals(align)) {
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
} else if (Excel.SYTLE_LEFT.equals(align)) {
style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
} else {
style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
}
 
cell.setCellStyle(style);
}
 
/**
* @param fileName
*            The fileName to set.
*/
private void setFileName(String fileName) {
this.fileName = fileName;
}
 
public void setShortCellNum(int shortCellNum) {
this.shortCellNum = shortCellNum;
}
}
 

你可能感兴趣的:(java,读写Excel)