依赖包下载: http://xiazai.VeVB.COm/201407/tools/java-excel-dependency(VeVB.COm).rar
Die Excel-Version von 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;import java.util.LinkedList;import java.util.List;import 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/> *有参构造函数参数为excel的全路径<br/> * * @author 宋立君 * @date 2014年07月03日 */public class ExcelUtil {// excel文件路径private String path = "";// Wenn Sie Excel verwenden, können Sie den Wert der Excel-Datei ändern.private boolean autoColumnWidth = false;/** * Der Wert wird angezeigt */public ExcelUtil() {}/** *有参构造函数 * * @param path * Excel-Datei */public ExcelUtil(String path) {this.path = path;}/** * 读取某个工作簿上的所有单元格的值。 * * @param BlattBestellung *工作簿序号,从0开始。 * @return List<Object[]> 所有单元格的值。 * @throws IOException * 加载excel文件IO异常。 * @throws FileNotFoundException * * @throws InvalidFormatException * @author Ausgabe * @date 03.07.2014 */public List<Object[]> read(int sheetOrder) throws FileNotFoundException,IOException, InvalidFormatException {FileInputStream fis = new FileInputStream(path);Workbook workbook = WorkbookFactory.create(fis);if (fis != null) {fis.close();}Sheet sheet = workbook.getSheetAt(sheetOrder);// ExcelList<Object []> valueList = new LinkedList<Object[]>();//循环遍历每一行、每一列.for (Row row : sheet) {// Die Funktion Object[] rowObject = null;for (Cell cell : row) {// cell.getCellType ist eine Funktion für den Typschalter von cell.getCellType (cell.getCellType()) {case Cell.CELL_TYPE_BOOLEAN:// Funktion „Boolean“ rowObject = CollectionUtil.addObjectToArray(rowObject,cell.getBooleanCellValue());break;case Cell.CELL_TYPE_NUMERIC:// Wenn Sie die Option if (DateUtil.isCellDateFormatted(cell)) verwenden möchten, verwenden Sie die Zeile rowObject = CollectionUtil.addObjectToArray(rowObject,cell.getDateCellValue());} else {DecimalFormat df = new DecimalFormat();//单元格的值,替换掉,String value = df.format(cell.getNumericCellValue()).replace(",", "");// 读取数字rowObject = CollectionUtil.addObjectToArray(rowObject,value);}break ;case Cell.CELL_TYPE_FORMULA:// Zurück zum AnfangrowObject = CollectionUtil.addObjectToArray(rowObject,cell.getCellFormula());break;case Cell.CELL_TYPE_STRING:// Zurück zum AnfangStringrowObject = CollectionUtil.addObjectToArray(rowObject, cell.getRichStringCellValue().toString());break; }}// Geben Sie eine Liste ein.valueList.add(rowObject);}return valueList;}/**工作簿序号, 从0开始. * @param colum * 列数 从1开始 * @param row * 行数 从1开始 * @return 单元格的始。 * @throws Exception * * @author 宋立君 * @date 03.07.2014 */public String read(int sheetOrder, int colum, int row) throws Exception {FileInputStream fis = new FileInputStream(path);Workbook workbook = WorkbookFactory.create (fis);if (fis != null) {fis.close();}Blatt sheet = workbook.getSheetAt(sheetOrder);Row rows = sheet.getRow(row - 1);Cell cell = rows.getCell(colum - 1);String content = cell.getStringCellValue() ;Inhalt zurückgeben;}/** *在指定的工作簿、行、列书写值。 * * @param sheetOrder * 工作簿序号,基于0. * @param colum * 列 基于1 * @param row * 行 基于1 * @param content * 将要被书写的内容. * @throws Exception * 书写后保存异常。 * @author 宋立君 * @date 03.07.2014 */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();}Sheet sheet = workbook.getSheetAt(sheetOrder);Row rows = sheet.createRow(row - 1);Cell cell = rows.createCell(colum - 1);cell.setCellValue(content);FileOutputStream fileOut = new FileOutputStream(path);workbook.write(fileOut);fileOut.close(); }/** * * * @param sheetOrder * 工作区序号* @return int Ausnahme. * @throws IOException * Die Excel-Version wird nicht angezeigt. * @throws InvalidFormatException * @author Ausgabe * @date 03.07.2014 */public int getSheetLastRowNum(int sheetOrder) throws IOException,InvalidFormatException {FileInputStream fis = new FileInputStream(path);Workbook workbook = WorkbookFactory.create(fis);if (fis != null) {fis.close();}Sheet sheet = workbook.getSheetAt(sheetOrder);return sheet.getLastRowNum();}/** *在磁盘生成一个含有内容的Excel, 路径为path属性 * * @param sheetName * 导出的sheet名称 * @param fieldName * 列名数组 * @param data * 数据组 * @throws IOException * @author 宋立君 * @date 2014年07月03日 */public void makeExcel(String sheetName, String[] fieldName,List<Object[]> data) throws IOException {// 在内存中生成工作薄HSSFWorkbook Arbeitsmappe = makeWorkBook(sheetName, fieldName, data);// String filePath = path.substring(0, path.lastIndexOf("//"));// Datei file = new File( filePath);// 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-Datei * @param sheetName * * sheet_sheet * @param fieldName * Datei * @param data * Datei * @param Antwort * Antwort * @throws IOException * IO-Fehler * @author 宋立君 * @date 03.07.2014 */public void makeStreamExcel(String excelName, String sheetName,String[] fieldName, List<Object[]> data,HttpServletResponse Response) throws IOException {OutputStream os = null;response.reset(); // 清空输出流os = Response.getOutputStream(); // Antwortresponse.setHeader("Content-disposition", "attachment; filename="+ new String(excelName.getBytes(), "ISO-8859-1")); // Zurück zum Anfang response.setContentType("application/msexcel"); // 定义输出类型// 在内存中生成工作薄HSSFWorkbook workbook = 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 collength[] = new Integer[fieldName.length];// 产生工作薄对象HSSFWorkbook workbook = new HSSFWorkbook();//产生工作表对象HSSFSheet sheet = workbook.createSheet();//产生一行HSSFRow row = sheet.createRow(0);// 产生单元格HSSFCell cell;// 写入各个字段的名称for (int i = 0; i < fieldName.length; i++) {//创建第一行各个字段名称的单元格cell = row.createCell((short) i);// // // 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.size(); i++) {Object[] tmp = data.get(i);// 生成一行row = sheet.createRow(i + 1);for (int j = 0; j < tmp.length; j++) {cell = row. createCell((short) j);// Gibt es einen Stringcell.setCellType(HSSFCell.CELL_TYPE_STRING);tempCellContent = (tmp[j] == null)? "" : tmp[j].toString();cell.setCellValue(new HSSFRichTextString(tempCellContent));// Identifizieren Sie den Wert, den Sie benötigen.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;}}}}}// Wird zur Laufzeit verwendet.if (autoColumnWidth) {// Wird zur Laufzeit verwendet.for (int i = 0; i < fieldName.length; i++) {sheet.setColumnWidth(i, collength[i] * 2 * 256);}}return workbook;}/** *功能:设置写入excel时,是否自动扩展列宽度来符合内容,默认为false。 * * @author 宋立君 * @date 2014年07月03日 * @param autoColumnWidth * true oder false */public void setAutoColumnWidth(boolean autoColumnWidth) {this.autoColumnWidth = autoColumnWidth;}}