다운로드 링크: http://xiazai.VeVB.COm/201407/tools/java-excel-dependent(VeVB.COm).rar
Excel 도구를 ExcelUtil.java源码:
패키지 com.itjh.javaUtil;가져오기 java.io.File;가져오기 java.io.FileInputStream;가져오기 java.io.FileNotFoundException;가져오기 java.io.FileOutputStream;가져오기 java.io.IOException;가져오기 java.io.OutputStream;가져오기 java.text.DecimalFormat;가져오기 java.util.LinkedList;가져오기 java.util.List;가져오기 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;가져오기 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 ;가져오기 org.apache.poi.ss.usermodel.Row;가져오기 org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.ss.usermodel.WorkbookFactory;/** * 封装对excel的操작품,包括本地读写excel과 流中输출exel,支持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/ > *宋立君 * @date 2014年07月03日 */public class ExcelUtil {// excel文件路径private String path = "";//写入excel时,是否自动扩认列宽島来符合内容。private boolean autoColumnWidth = false;/** * 无参构造函数 默认 */public ExcelUtil() {}/** * 있음 시트주문 *工作簿序号,从0开始。 * @return List<Object[]> 所有单元格的值。 * @throws IOException * 加载excel文件IO异常。 * @throws FileNotFoundException * excel文件没有找到异常。 * @throws InvalidFormatException * @author 宋立君 * @date 2014年07月03日 */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();}시트 시트 = workbook.getSheetAt(sheetOrder);// 用来记录excel值List<Object[]> valueList = new LinkedList<Object[]>();// 循环遍历每一行、每一列。for (행 행 : 시트) {// 每一行Object[] rowObject = null;for (Cell cell : row) {// cell.getCellType是获得cell里face 保存的值的typeswitch (cell.getCellType()) {case Cell.CELL_TYPE_BOOLEAN:// 得到Boolean对象적 방법rowObject = CollectionUtil.addObjectToArray( rowObject,cell.getBooleanCellValue());break;case Cell.CELL_TYPE_NUMERIC:// 先看是否是日期格式if (DateUtil.isCellDateFormatted(cell)) {// 读取日期格式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:// 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 宋立君 * @date 2014年07月03日 */public 끈 read(int sheetOrder, int colum, int row)는 예외를 발생시킵니다. {FileInputStream fis = new FileInputStream(path);Workbook workbook = WorkbookFactory.create(fis);if (fis != null) {fis.close();}시트 시트 = workbook.getSheetAt(sheetOrder);행 행 = sheet.getRow(row - 1);셀 셀 =rows.getCell(colum - 1);String content = cell.getStringCellValue();return content;}/** * 에서 즐비한 작업을 수행합니다. * @param colum * 列 基于1 * @param row * 行 基于1 * @param content * 将要被书写的内容。 * @throws Exception * 书写后保存异常。 * @author 宋立君 * @date 2014년 7월 3일 */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();}시트 시트 = workbook.getSheetAt(sheetOrder);행 행 = sheet.createRow(행 - 1);셀 셀 =rows.createCell(열 - 1);cell.setCellValue(content);FileOutputStream fileOut = new FileOutputStream(경로);workbook.write(fileOut);fileOut.close(); }/** *得到一个工作区最后一条记录的序号,相当于这个工作簿共多少行数据。 * * @param sheetOrder * 工작품区序号 * @return int 序号。 * @throws IOException * 根据excel路径加载excel异常。 * @throws InvalidFormatException * @author 宋立君 * @date 2014年07月03日 */public int getSheetLastRowNum(int sheetOrder) throws IOException,InvalidFormatException {FileInputStream fis = new FileInputStream(경로);통합 문서 통합 문서 = WorkbookFactory.create(fis);if (fis != null) {fis.close();}시트 시트 = workbook.getSheetAt(sheetOrder);return sheet.getLastRowNum();}/* * * 재고 있는 엑셀, 路径为path属性 * * @param sheetName * 导出的sheetname称 * @param fieldName * 列name数组 * @param data * 数据组 * @throws IOException * @author 宋立君 * @date 2014년 7월 3일 */public void makeExcel(String sheetName, String[] fieldName,List<Object[]> data) throws IOException {// 在内存中生成工作薄HSSFWorkbook workbook = makeWorkBook(sheetName, fieldName, data) ;// 截取文件夹路径String filePath = path.substring(0, path.lastIndexOf("//"));// 如果路径不存在,创建路径File 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();}/** * 에서 출력 중입니다. * * @param excelName * 출력된 Excel 이름 包括扩 확장 이름 * @param sheetName * 출력 시트 이름 * @param fieldName * 이름 이름 * @param data *数据组 * @param 응답 * 응답 * @throws IOException * 转换流时IO错误 * @author 宋立君 * @date 2014年07月03日 */public void makeStreamExcel(String excelName, String sheetName,String[] fieldName, List< Object[]> 데이터, HttpServletResponse 응답)에서 IOException이 발생합니다. {OutputStream os = null;response.reset(); // 전체 공간 출력 = response.getOutputStream(); // 取得输流response.setHeader("Content-disposition", "attachment; filename="+ new String(excelName.getBytes(), "ISO-8859-1")); // 设정정보출문件头response.setContentType("application/msexcel"); // 정의 출력 결과// 에서 内存中生成工作薄HSSFWorkbook workbook = makeWorkBook(sheetName, fieldName, data);os.flush();workbook.write(os);}/** * 根据条件,生成工作薄对象到内存。 * * @param sheetName * 工作表对象name称 * @param fieldName * 首列列name称 * @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();// 为了工작품表能支持中文,设置字符集为UTF_16workbook.setSheetName(0, sheetName);// 产生一行HSSFRow row = sheet.createRow(0);// 产生单元格HSSFCell cell;// 写入各个字段的name称for (int i = 0; i < fieldName.length; i++) {// 创建第一行各个字段name称的单元格셀 = row.createCell((짧은) i);// 设置单元格内容为字符串型cell.setCellType(HSSFCell.CELL_TYPE_STRING);//为了能는 单元格中输入中文,设置字符集为UTF_16// cell.setEncoding(HSSFCell.ENCODING_UTF_16);// 给单元格内容赋值cell.setCellValue(new HSSFRichTextString(fieldName[i]));// 初始化列宽collength[i] = fieldName[i].getBytes().length;}// 临时单元格内容String tempCellContent = "";// (int i = 0; 나는 < 데이터.크기(); i++) {Object[] tmp = data.get(i);// 生成一行row = sheet.createRow(i + 1);for (int j = 0; j < tmp.length; j++) {cell = row. createCell((짧은) j);//设置单元格字符类型为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;}}}}} //自动调整列宽degree.if (autoColumnWidth) {// 调整列为这列文字对应的最大宽titude.for (int i = 0; i < fieldName.length; i++) {sheet.setColumnWidth(i, collength[i] * 2 * 256);}}반환 workbook;}/** * 功能:设置写入excel时,是否自动扩展列宽島来符内容,默认为false。 * * @author 宋立君 * @date 2014年07月03日 * @param autoColumnWidth * true 또는 false */public void setAutoColumnWidth(boolean autoColumnWidth) {this.autoColumnWidth = autoColumnWidth;}}