程序人生  
我们站在同一起跑线上,让我们共同努力,共同奋进,愿您的人生因程序而美好!
日历
<2014年9月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011
统计
  • 随笔 - 0
  • 文章 - 38
  • 评论 - 8
  • 引用 - 0

导航

留言簿(2)

文章分类

文章档案

常用Web 站点

搜索

  •  

最新评论

 
    最近做试题导入导出,选用了poi导入和导出excel文件,直接用poi的API感觉代码很混乱,耦合度很高,所以封装了两个底层类。一个是ExcelReader:主要包含读取excel内容的方法;另一个是ExcelWriter:主要包含几个生成excel文件的方法。现贴出来供大家以后参考使用:

1、ExcelWriter.java
package com.eruite.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
 * @author caihua
 */
public class ExcelReader {
 private HSSFWorkbook wb = null;// book [includes sheet]

 private HSSFSheet sheet = null;

 private HSSFRow row = null;

 private int sheetNum = 0; // 第sheetnum个工作表

 private int rowNum = 0;

 private FileInputStream fis = null;

 private File file = null;

 public ExcelReader() {
 }

 public ExcelReader(File file) {
  this.file = file;
 }

 public void setRowNum(int rowNum) {
  this.rowNum = rowNum;
 }

 public void setSheetNum(int sheetNum) {
  this.sheetNum = sheetNum;
 }

 public void setFile(File file) {
  this.file = file;
 }

 /**
  * 读取excel文件获得HSSFWorkbook对象
  */
 public void open() throws IOException {
  fis = new FileInputStream(file);
  wb = new HSSFWorkbook(new POIFSFileSystem(fis));
  fis.close();
 }

 /**
  * 返回sheet表数目
  *
  * @return int
  */
 public int getSheetCount() {
  int sheetCount = -1;
  sheetCount = wb.getNumberOfSheets();
  return sheetCount;
 }

 /**
  * sheetNum下的记录行数
  *
  * @return int
  */
 public int getRowCount() {
  if (wb == null)
   System.out.println("=============>WorkBook为空");
  HSSFSheet sheet = wb.getSheetAt(this.sheetNum);
  int rowCount = -1;
  rowCount = sheet.getLastRowNum();
  return rowCount;
 }

 /**
  * 读取指定sheetNum的rowCount
  *
  * @param sheetNum
  * @return int
  */
 public int getRowCount(int sheetNum) {
  HSSFSheet sheet = wb.getSheetAt(sheetNum);
  int rowCount = -1;
  rowCount = sheet.getLastRowNum();
  return rowCount;
 }

 /**
  * 得到指定行的内容
  *
  * @param lineNum
  * @return String[]
  */
 public String[] readExcelLine(int lineNum) {
  return readExcelLine(this.sheetNum, lineNum);
 }

 /**
  * 指定工作表和行数的内容
  *
  * @param sheetNum
  * @param lineNum
  * @return String[]
  */
 public String[] readExcelLine(int sheetNum, int lineNum) {
  if (sheetNum < 0 || lineNum < 0)
   return null;
  String[] strExcelLine = null;
  try {
   sheet = wb.getSheetAt(sheetNum);
   row = sheet.getRow(lineNum);

   int cellCount = row.getLastCellNum();
   strExcelLine = new String[cellCount + 1];
   for (int i = 0; i <= cellCount; i++) {
    strExcelLine[i] = readStringExcelCell(lineNum, i);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return strExcelLine;
 }

 /**
  * 读取指定列的内容
  *
  * @param cellNum
  * @return String
  */
 public String readStringExcelCell(int cellNum) {
  return readStringExcelCell(this.rowNum, cellNum);
 }

 /**
  * 指定行和列编号的内容
  *
  * @param rowNum
  * @param cellNum
  * @return String
  */
 public String readStringExcelCell(int rowNum, int cellNum) {
  return readStringExcelCell(this.sheetNum, rowNum, cellNum);
 }

 /**
  * 指定工作表、行、列下的内容
  *
  * @param sheetNum
  * @param rowNum
  * @param cellNum
  * @return String
  */
 public String readStringExcelCell(int sheetNum, int rowNum, int cellNum) {
  if (sheetNum < 0 || rowNum < 0)
   return "";
  String strExcelCell = "";
  try {
   sheet = wb.getSheetAt(sheetNum);
   row = sheet.getRow(rowNum);

   if (row.getCell((short) cellNum) != null) { // add this condition
    // judge
    switch (row.getCell((short) cellNum).getCellType()) {
    case HSSFCell.CELL_TYPE_FORMULA:
     strExcelCell = "FORMULA ";
     break;
    case HSSFCell.CELL_TYPE_NUMERIC: {
     strExcelCell = String.valueOf(row.getCell((short) cellNum)
       .getNumericCellValue());
    }
     break;
    case HSSFCell.CELL_TYPE_STRING:
     strExcelCell = row.getCell((short) cellNum)
       .getStringCellValue();
     break;
    case HSSFCell.CELL_TYPE_BLANK:
     strExcelCell = "";
     break;
    default:
     strExcelCell = "";
     break;
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return strExcelCell;
 }

 public static void main(String args[]) {
  File file = new File("C:\\qt.xls");
  ExcelReader readExcel = new ExcelReader(file);
  try {
   readExcel.open();
  } catch (IOException e) {
   e.printStackTrace();
  }
  readExcel.setSheetNum(0); // 设置读取索引为0的工作表
  // 总行数
  int count = readExcel.getRowCount();
  for (int i = 0; i <= count; i++) {
   String[] rows = readExcel.readExcelLine(i);
   for (int j = 0; j < rows.length; j++) {
    System.out.print(rows[j] + " ");
   }
   System.out.print("\n");
  }
 }
}

2、ExcelWriter.java

package com.eruite.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * 生成导出Excel文件对象
 *
 * @author caihua
 *
 */
public class ExcelWriter {
 // 设置cell编码解决中文高位字节截断
 private static short XLS_ENCODING = HSSFCell.ENCODING_UTF_16;

 // 定制浮点数格式
 private static String NUMBER_FORMAT = "#,##0.00";

 // 定制日期格式
 private static String DATE_FORMAT = "m/d/yy"; // "m/d/yy h:mm"

 private OutputStream out = null;

 private HSSFWorkbook workbook = null;

 private HSSFSheet sheet = null;

 private HSSFRow row = null;

 public ExcelWriter() {
 }

 /**
  * 初始化Excel
  *
  */
 public ExcelWriter(OutputStream out) {
  this.out = out;
  this.workbook = new HSSFWorkbook();
  this.sheet = workbook.createSheet();
 }

 /**
  * 导出Excel文件
  *
  * @throws IOException
  */
 public void export() throws FileNotFoundException, IOException {
  try {
   workbook.write(out);
   out.flush();
   out.close();
  } catch (FileNotFoundException e) {
   throw new IOException(" 生成导出Excel文件出错! ", e);
  } catch (IOException e) {
   throw new IOException(" 写入Excel文件出错! ", e);
  }

 }

 /**
  * 增加一行
  *
  * @param index
  *            行号
  */
 public void createRow(int index) {
  this.row = this.sheet.createRow(index);
 }

 /**
  * 获取单元格的值
  *
  * @param index
  *            列号
  */
 public String getCell(int index) {
  HSSFCell cell = this.row.getCell((short) index);
  String strExcelCell = "";
  if (cell != null) { // add this condition
   // judge
   switch (cell.getCellType()) {
   case HSSFCell.CELL_TYPE_FORMULA:
    strExcelCell = "FORMULA ";
    break;
   case HSSFCell.CELL_TYPE_NUMERIC: {
    strExcelCell = String.valueOf(cell.getNumericCellValue());
   }
    break;
   case HSSFCell.CELL_TYPE_STRING:
    strExcelCell = cell.getStringCellValue();
    break;
   case HSSFCell.CELL_TYPE_BLANK:
    strExcelCell = "";
    break;
   default:
    strExcelCell = "";
    break;
   }
  }
  return strExcelCell;
 }

 /**
  * 设置单元格
  *
  * @param index
  *            列号
  * @param value
  *            单元格填充值
  */
 public void setCell(int index, int value) {
  HSSFCell cell = this.row.createCell((short) index);
  cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
  cell.setCellValue(value);
 }

 /**
  * 设置单元格
  *
  * @param index
  *            列号
  * @param value
  *            单元格填充值
  */
 public void setCell(int index, double value) {
  HSSFCell cell = this.row.createCell((short) index);
  cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
  cell.setCellValue(value);
  HSSFCellStyle cellStyle = workbook.createCellStyle(); // 建立新的cell样式
  HSSFDataFormat format = workbook.createDataFormat();
  cellStyle.setDataFormat(format.getFormat(NUMBER_FORMAT)); // 设置cell样式为定制的浮点数格式
  cell.setCellStyle(cellStyle); // 设置该cell浮点数的显示格式
 }

 /**
  * 设置单元格
  *
  * @param index
  *            列号
  * @param value
  *            单元格填充值
  */
 public void setCell(int index, String value) {
  HSSFCell cell = this.row.createCell((short) index);
  cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  cell.setEncoding(XLS_ENCODING);
  cell.setCellValue(value);
 }

 /**
  * 设置单元格
  *
  * @param index
  *            列号
  * @param value
  *            单元格填充值
  */
 public void setCell(int index, Calendar value) {
  HSSFCell cell = this.row.createCell((short) index);
  cell.setEncoding(XLS_ENCODING);
  cell.setCellValue(value.getTime());
  HSSFCellStyle cellStyle = workbook.createCellStyle(); // 建立新的cell样式
  cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(DATE_FORMAT)); // 设置cell样式为定制的日期格式
  cell.setCellStyle(cellStyle); // 设置该cell日期的显示格式
 }

 public static void main(String[] args) {
  System.out.println(" 开始导出Excel文件 ");

  File f = new File("C:\\qt.xls");
  ExcelWriter e = new ExcelWriter();

  try {
   e = new ExcelWriter(new FileOutputStream(f));
  } catch (FileNotFoundException e1) {
   e1.printStackTrace();
  }

  e.createRow(0);
  e.setCell(0, "试题编码 ");
  e.setCell(1, "题型");
  e.setCell(2, "分值");
  e.setCell(3, "难度");
  e.setCell(4, "级别");
  e.setCell(5, "知识点");

  e.createRow(1);
  e.setCell(0, "t1");
  e.setCell(1, 1);
  e.setCell(2, 3.0);
  e.setCell(3, 1);
  e.setCell(4, "重要");
  e.setCell(5, "专业");

  try {
   e.export();
   System.out.println(" 导出Excel文件[成功] ");
  } catch (IOException ex) {
   System.out.println(" 导出Excel文件[失败] ");
   ex.printStackTrace();
  }
 }

}

posted on 2007-12-02 23:08 蔡华林 阅读(10476) 评论(6)  编辑  收藏 所属分类: javatool
评论:
  • # re: 使用POI导入和导出Excel文件  zhongjiaren110 Posted @ 2008-05-12 14:50
    好贴,我顶!  回复  更多评论   

  • # Seoclick  Seoclick Posted @ 2009-05-18 21:09
    Hi everyone. You need only reflect that one of the best ways to get yourself a reputation as a dangerous citizen these days is to go about repeating the very phrases which our founding fathers used in the struggle for independence.
    I am from Sri and also am speaking English, tell me right I wrote the following sentence: "Website seo services, organic seo affordable seo website design los angeles specializing in top notch internet search engine marketing and organic small.Search engine marketing services for small and medium sized businesses."

    :( Thanks in advance. Jolanta.  回复  更多评论   

  • # re: 使用POI导入和导出Excel文件  zm Posted @ 2009-12-22 15:51
    谢谢  回复  更多评论   

  • # re: 使用POI导入和导出Excel文件  lovejavaevil Posted @ 2010-05-31 16:14
    首先非常要感谢作者的拿这好东西分享出来,本人很少评论别人的博客,但是作者的编程风格是我在网上见过最好的,我要向作者学习。  回复  更多评论   

  • # re: 使用POI导入和导出Excel文件[未登录]  lucky Posted @ 2010-07-28 14:56
    谢谢楼主了啊,写的相当的不错。。  回复  更多评论   

  • # re: 使用POI导入和导出Excel文件  夜雨潇潇故地游 Posted @ 2014-09-29 13:18
    首先非常要感谢作者的拿这好东西分享出来,本人很少评论别人的博客,但是作者的编程风格是我在网上见过最好的,我要向作者学习。 +1  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
博客园   IT新闻   Chat2DB   C++博客   博问  
 
 
Copyright © 蔡华林 Powered by: 博客园 模板提供:沪江博客