Contoh: http://xiazai.VeVB.COM/201407/tools/java-excel-dependency(VeVB.COM).rar
Fitur ExcelUtil.java:
paket com.itjh.javaUtil;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.text.DecimalFormat;impor java.util.LinkedList;impor java.util.List;impor javax.servlet.http.HttpServletResponse;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFrichTextString;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.openxml4j.Exceptions.InvalidFormatException;import org.apache.poi.ss.usermodel.Cell ;import org.apache.poi.ss.usermodel.DateUtil;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.ss.usermodel.WorkbookFactory ;/** *封装对excel的操作,包括本地读写excel和流中输出excel,支持office 2007。<br/> *依赖于poi-3.9-20121203.jar,poi-ooxml-3.9-20121203.jar,poi-ooxml-schemas-3.9- * 20121203.jar,dom4j-1.6.1.jar<br/> * ExcelUtil {// excel文件路径private String path = "";//写入excel时,是否自动扩展列宽度来符合内容。private boolean autoColumnWidth = false;/** * 无参构造函数 默认 */public ExcelUtil() {}/** *有参构造函数 * * @param path * excel路径 */public ExcelUtil(String path) {this.path = path;}/** * 读取某个工作簿上的所有单元格的值。 * * @param lembarPesanan *工作簿序号,从0开始。 * @return List<Object[]> 所有单元格的值。 * @throws IOException * 加载excel文件IO异常。 * @throws FileNotFoundException * excel文件没有找到异常。 * @throws InvalidFormatException * @author 宋立君 * @tanggal 2014年07月03日 */public List<Object[]> read(int sheetOrder) throws FileNotFoundException,IOException, InvalidFormatException {FileInputStream fis = new FileInputStream(path);Buku kerja buku kerja = WorkbookFactory.create(fis);if (fis != null) {fis.close();}Sheet sheet = workbook.getSheetAt(sheetOrder);// 用来记录excel值List<Object []> Daftar Nilai = Daftar Tertaut baru<Objek[]>();//循环遍历每一行、每一列。for (Baris baris : lembar) {// 每一行Object[] rowObject = null;for (Sel sel : baris) {// cell.getCellType是获得cell里面保存的值的typeswitch (cell.getCellType()) {case Cell.CELL_TYPE_BOOLEAN:// 得到Boolean对象的方法rowObject = CollectionUtil.addObjectToArray(rowObject,cell.getBooleanCellValue());break;case Cell.CELL_TYPE_NUMERIC://先看是否是日期格式if (DateUtil.isCellDateFormatted(sel)) {// 读取日期格式rowObject = CollectionUtil.addObjectToArray(rowObject,cell.getDateCellValue());} else {DecimalFormat df = new DecimalFormat();// Misalnya, Nilai string = df.format(cell.getNumericCellValue()).replace(",", "");// 读取数字rowObject = CollectionUtil.addObjectToArray(rowObject,value);}break ;kasus Sel.CELL_TYPE_FORMULA:// rowObject = CollectionUtil.addObjectToArray(rowObject,cell.getCellFormula());break;case Cell.CELL_TYPE_STRING:// 读取StringrowObject = CollectionUtil.addObjectToArray(rowObject, cell.getRichStringCellValue().toString());break; }}//将这行添加到list。valueList.add(rowObject);}return valueList;}/** * 读取某个工作簿上的某个单元格的值。 * * @param sheetOrder *工作簿序号,从0开始。 * @param colum * 列数 从1开始 * @param row * 行数 从1开始 * @return 单元格的值。 * @throws Exception *加载excel异常。 * @author 宋立君 * @tanggal 2014年07月03日 */public String read(int sheetOrder, int colum, int row) melempar Pengecualian {FileInputStream fis = new FileInputStream(path);Workbook workbook = WorkbookFactory.create (fis);jika (fis != null) {fis.close();}Sheet sheet = workbook.getSheetAt(sheetOrder);Baris baris = sheet.getRow(row - 1);Sel sel = baris.getCell(kolom - 1);Isi string = sel .getStringCellValue();mengembalikan konten;}/** *在指定的工作簿、行、列书写值。 * * @param sheetOrder * 工作簿序号,基于0. * @param colum * 列 基于1 * @param row * 行 基于1 * @param content * 将要被书写的内容。 * @throws Exception * 书写后保存异常。 * @author 宋立君* @tanggal 2014年07月03日 */public void write(int sheetOrder, int colum, int row, String content)throws Exception {FileInputStream fis = new FileInputStream(path);Workbook workbook = WorkbookFactory.create(fis);if (fis != null) {fis.close();}Lembar lembar = workbook.getSheetAt(sheetOrder);Baris baris = sheet.createRow(baris - 1);Sel sel = baris.createCell(kolom - 1);sel.setCellValue(konten);FileOutputStream fileOut = new FileOutputStream(path);workbook.write (fileOut);fileOut.close();}/** *得到一个工作区最后一条记录的序号,相当于这个工作簿共多少行数据。 * * @param sheetOrder *工作区序号 * @return int 序号。 * @throws IOException * 根据excel路径加载excel异常。 * @throws InvalidFormatException * @author 宋立君 * @tanggal 2014年07月03日*/public int getSheetLastRowNum(int sheetOrder) menampilkan IOException,InvalidFormatException {FileInputStream fis = new FileInputStream(path);Buku kerja buku kerja = WorkbookFactory.create(fis);if (fis != null) {fis.close();}Lembar lembar = workbook.getSheetAt(sheetOrder);return sheet.getLastRowNum();}/** *在磁盘生成一个含有内容的excel,路径为path属性 * * @param sheetName * 导出的sheet名称 * @param fieldName * 列名数组 * @param data * 数据组 * @throws IOException * @author 宋立君 * @tanggal 2014年07月03日 */public void makeExcel(String sheetName, String[] fieldName,List<Object[]> data) throws IOException {// 在内存中生成工作薄HSSFWorkbook buku kerja = makeWorkBook(sheetName, fieldName, data);// 截取文件夹路径String filePath = path.substring(0, path.lastIndexOf("//"));// 如果路径不存在,创建路径File file = File baru( jalur file);// System.out.println(path+"-----------"+file.exists());if (!file.exists())file.mkdirs();FileOutputStream fileOut = new FileOutputStream(path );workbook.write(fileOut);fileOut.close();}/** * 在输出流中导出excel。 * * @param excelName * 导出的excel名称 包括扩展名 * @param sheetName * 导出的sheet名称 * @param fieldName * 列名数组 * @param data * 数据组 * @param respon * respon * @throws IOException *转换流时IO错误 * @author 宋立君 * @tanggal 2014年07月03日 */public void makeStreamExcel(String excelName, String sheetName,String[] fieldName, List<Object[]> data,HttpServletResponse respon) melempar IOException {OutputStream os = null;respons.reset(); // 清空输出流os = respon.getOutputStream(); // 取得输出流response.setHeader("Content-disposition", "attachment; filename="+ new String(excelName.getBytes(), "ISO-8859-1")); // 设定输出文件头response.setContentType("application/msexcel"); // 定义输出类型// 在内存中生成工作薄HSSFWorkbook buku kerja = makeWorkBook(sheetName, fieldName, data);os.flush();workbook.write(os);}/** *根据条件,生成工作薄对象到内存。 * * @param sheetName * 工作表对象名称 * @param fieldName * 首列列名称 * @param data * 数据 * @return HSSFWorkbook * @author 宋立君 * @date 2014年07月03日 */private HSSFWorkbook makeWorkBook(String sheetName, String[] fieldName,List<Object[]> data) {//用来记录最大列宽,自动调整列宽。Integer colllength[] = new Integer[fieldName.length];// 产生工作薄对象HSSFWorkbook workbook = new HSSFWorkbook();// Lembar HSSFSheet = workbook.createSheet();// UTF_16workbook.setSheetName(0, sheetName);//产生一行HSSFRow row = sheet.createRow(0);// 产生单元格HSSFCell cell;// 写入各个字段的名称for (int i = 0; i < fieldName.length; i++) {//创建第一行各个字段名称的单元格cell = row.createCell((short) i);// fungsi cell.setCellType(HSSFCell.CELL_TYPE_STRING);// // cell.setEncoding(HSSFCell.ENCODING_UTF_16);//给单元格内容赋值cell.setCellValue(new HSSFRichTextString(fieldName[i]));// 初始化列宽collength[i] = fieldName[i].getBytes().length;}// 临时单元格内容String tempCellContent = "";// 写入各条记录,每条记录对应excel表中的一行for (int i = 0; i < data.ukuran(); i++) {Objek[] tmp = data.get(i);// 生成一行row = sheet.createRow(i + 1);for (int j = 0; j < tmp.length; j++) {sel = baris. createCell((pendek) j);// Bagaimana cara menggunakan Stringcell.setCellType(HSSFCell.CELL_TYPE_STRING);tempCellContent = (tmp[j] == null) ? "" : tmp[j].toString();cell.setCellValue(new HSSFrichTextString(tempCellContent));// 如果自动调整列宽度。if (autoColumnWidth) {if (j >= collength.length) {//标题列数小于数据列数时。collength = CollectionUtil.addObjectToArray(collength,tempCellContent.getBytes().length);} else {// if (collength[j] < tempCellContent.getBytes().length) {collength[j] = tempCellContent.getBytes().length;}}}}}// 自动调整列宽度。if (autoColumnWidth) {// 调整列为这列文字对应的最大宽度。for (int i = 0; i < fieldName.length; i++) {sheet.setColumnWidth(i, colllength[i] * 2 * 256);}}kembalikan buku kerja;}/** *功能:设置写入excel时,是否自动扩展列宽度来符合内容,默认为false。 * * @author 宋立君 * @date 2014年07月03日 * @param autoColumnWidth * true或者false */public void setAutoColumnWidth(boolean autoColumnWidth) {this.autoColumnWidth = autoColumnWidth;}}