java POI读取Excel 2003/2007/2010

java POI方法支持读写”.xls”、”.xlsx”两种格式,调用时需引入相应jar包
poi-3.14.jar、poi-ooxml-3.14.jar、poi-ooxml-schemas-3.14.jar、xmlbeans-2.6.0.jar

  • 读写”.xls”格式使用org.apache.poi.hssf.usermodel.*包的内容,例如:HSSFWorkbook
  • 读写”.xlsx”格式使用org.apache.poi.xssf.usermodel.*包的内容,例如:XSSFWorkbook
  • 读取两种格式使用org.apache.poi.ss.usermodel.*包的内容,例如:Workbook

读取Excel

兼容 Excel 2003/2007/2010

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;

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;//poi-3.14.jar
import org.apache.poi.ss.usermodel.WorkbookFactory;//poi-ooxml-3.14.jar
/**
 * 读取Excel 兼容2003/2007/2010
 * @author: xuexuan
 * 2016-11-9 下午6:37:42 
 * void
 */
public static void readExcel() {
    try {
        File file = new File("D:/test.xlsx");// 创建文件对象
        FileInputStream in = new FileInputStream(file);// 创建文件流
        Workbook book = WorkbookFactory.create(in);// Workbook方式读取,兼容.xls .xlsx两种格式
        int sheetNum = book.getNumberOfSheets();// 获取Excel文件里工作簿sheet数量
        // 遍历每个sheet
        for (int s = 0; s < sheetNum; s++) {
            Sheet sheet = book.getSheetAt(s);
            int rowNum = sheet.getPhysicalNumberOfRows();// 获取总行数
            // 遍历每一行
            for (int r = 0; r < rowNum; r++) {
                Row row = sheet.getRow(r);
                int cellNum = row.getPhysicalNumberOfCells();// 获取总列数
                // 遍历每一列
                for (int c = 0; c < cellNum; c++) {
                    Cell cell = row.getCell(c);
                    int cellType = cell.getCellType();// 获取文本类型
                    String cellValue = "";// 文本值
                    switch (cellType) {
                        case Cell.CELL_TYPE_STRING:// 文本
                            cellValue = cell.getStringCellValue();
                            break;
                        case Cell.CELL_TYPE_NUMERIC:// 数字、日期
                            if (DateUtil.isCellDateFormatted(cell)) {// 日期型
                                SimpleDateFormat fm = new SimpleDateFormat("yyy-MM-dd");
                                cellValue = fm.format(cell.getDateCellValue());
                            } else {// 数字型
                                cellValue = cell.getNumericCellValue() + "";
                            }
                            break;
                        case Cell.CELL_TYPE_BOOLEAN:// 布尔型
                            cellValue = cell.getBooleanCellValue() + "";
                            break;
                        case Cell.CELL_TYPE_BLANK://空白 按文本处理
                            cellValue = cell.getStringCellValue();
                            break;
                        case Cell.CELL_TYPE_ERROR:// 错误
                            cellValue = "错误";
                            break;
                        default:
                            cellValue = "错误";
                    }
                    System.out.println(cellValue);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

【注】

  • POI可以读取excel里面的怪字符,例如海外的一些西语重音:á、é、í、ó、ú等,不会出现乱码情况。但是用jxl读取,若不指定读取编码则会出现乱码。
WorkbookSettings setting = new WorkbookSettings();
setting.setEncoding("iso-8859-1");// 指定Excel读取编码,解决频道名含海外的一些西语重音如á、é、í、ó、ú等出现乱码情况
Workbook wb = Workbook.getWorkbook(is, setting);

写入Excel.xls

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;// javax.servlet-api-3.1.0.jar

import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;// poi-3.14.jar
/**
 * HSSFWorkbook写入xls文件
 * @author: xuexuan
 * 2016-11-9 下午7:53:24 
 */
public static void writeExcel_xls() {
    HSSFWorkbook book = new HSSFWorkbook();// 创建工作文档对象
    Sheet sheet = book.createSheet("sheet1");// 创建工作簿
    // 设置默认宽、高
    sheet.setDefaultRowHeightInPoints(20.0F);
    sheet.setDefaultColumnWidth(22);
    // 创建数据
    Row row;
    Cell cell;
    // 表头
    // 1.1创建表头样式
    CellStyle headStyle = book.createCellStyle();
    headStyle.setBorderBottom((short) 1);
    headStyle.setBorderLeft((short) 1);
    headStyle.setBorderRight((short) 1);
    headStyle.setBorderTop((short) 1);
    headStyle.setAlignment((short) 2);
    headStyle.setVerticalAlignment((short) 1);
    HSSFFont font = book.createFont();// 设置字体
    font.setFontName("宋体");
    font.setFontHeightInPoints((short) 12);
    font.setBoldweight((short) 700);
    headStyle.setFont(font);
    // 1.2创建表头内容
    int cellIndex = 0;
    String[] heads = { "姓名", "年龄" };
    row = sheet.createRow(0);// 创建表头行
    for (String head : heads) {
        cell = row.createCell(cellIndex);// 创建表头各列
        cell.setCellValue(head);// 赋值
        cell.setCellStyle(headStyle);// 赋样式
        cellIndex++;
    }
    // 数据
    // 1.1创建数据样式
    CellStyle contentStyle = book.createCellStyle();
    HSSFFont contentFont = book.createFont();// 设置字体
    contentFont.setFontName("宋体");
    contentFont.setFontHeightInPoints((short) 12);
    contentFont.setBoldweight((short) 400);
    contentStyle.setFont(font);
    // 1.2创建表格内容
    for (int r = 1; r < 5; r++) {
        row = sheet.createRow(r);// 创建数据行
        for (int c = 0; c < 2; c++) {
            cell = row.createCell(c);// 创建数据各列
            cell.setCellValue("数据" + r + c);// 赋值
            cell.setCellStyle(contentStyle);// 赋样式
        }
    }

    // 第一种方式:写入文件
    try {
        // 创建文件流
        OutputStream out = new FileOutputStream("D:" + File.separator + "out.xls");
        // 写入数据
        book.write(out);
        // 关闭文件流
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    // 第二种方式:Web工程导出Excel,属于服务器端生成.xls格式的文件返回为用户
    HttpServletResponse response = null;
    try {// 设置返回头信息
        String fileName = new String("out.xls".getBytes(), "ISO8859-1");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");// 指定Content-Type:application/vnd.ms-excel ,浏览器就会提示要下载的文件是excel文件。
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {// 将数据写入返回流
        OutputStream out = response.getOutputStream();
        book.write(out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

写入Excel.xlsx

import org.apache.poi.xssf.usermodel.XSSFWorkbook;//poi-ooxml-3.14.jar
/**
 * XSSFWorkbook写入xlsx文件
 * @author: xuexuan
 * 2016-11-9 下午8:48:01 
 */
public static void writeExcel_xlsx() {
    XSSFWorkbook book = new XSSFWorkbook();
    Sheet sheet = book.createSheet("sheet1");
    // 创建数据
    Row row;
    Cell cell;
    for (int r = 0; r < 5; r++) {
        row = sheet.createRow(r);// 创建数据行
        for (int c = 0; c < 2; c++) {
            cell = row.createCell(c);// 创建数据各列
            cell.setCellValue("数据" + r + c);// 赋值
        }
    }
    // 写入文件
    try {
        // 创建文件流
        OutputStream out = new FileOutputStream("D:" + File.separator + "out.xlsx");
        // 写入数据
        book.write(out);
        // 关闭文件流
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值