导入导出Excel文件

    起先,以为实现导入导出的是js插件。后来了解到原来我大java就能操作excel文件。

    java操作excel文件还是比较简单的,不过要导入两个包(使用maven)

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>

     需要注意的是excel 2003和excel 2007及以上的文件格式是不一样的,上段代码中poi就是操作excel 2003的HSSFWorkbook(HSSF开头), poi-ooxml是操作excel 2007及以上的XSSF开头的类。


  话不多说,直接上代码:

1. 先写个判断文件类型的工具类:

public class CEVUtil {

    /**
     * 依据后缀名判断读取的是否为Excel文件
     * @param filePath
     * @return
     */
    public static boolean isExcel(String filePath){
        if(filePath.matches("^.+\\.(?i)(xls)$")||filePath.matches("^.+\\.(?i)(xlsx)$")){
            return true;
        }
        return false;
    }

    /**
     * 检查文件是否存在
     */
    public static boolean fileExist(String filePath){
        if(filePath == null || filePath.trim().equals("")) return false;
        File file = new File(filePath);
        if (file == null || !file.exists()){
            return false;
        }
        return true;
    }
    /**
     * 依据内容判断是否为excel2003及以下
     */
    public static boolean isExcel2003(String filePath){
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
            if(POIFSFileSystem.hasPOIFSHeader(bis)) {
                System.out.println("Excel版本为excel2003及以下");
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }
    /**
     * 依据内容判断是否为excel2007及以上
     */
    public static boolean isExcel2007(String filePath){
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
            if(POIXMLDocument.hasOOXMLHeader(bis)) {
                System.out.println("Excel版本为excel2007及以上");
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }
}

2.  操作excel的类

public class FileController {

    /** 错误信息 */
    private String errorInfo;

    /**
     * 验证EXCEL文件是否合法
     */
    public boolean validateExcel(String filePath){

        /**判断文件名是否为空或者文件是否存在 */
        if(!CEVUtil.fileExist(filePath)){
            errorInfo = "文件不存在";
            return false;
        }

        /**检查文件是否是Excel格式的文件 */
        if (!CEVUtil.isExcel(filePath))  {
            errorInfo = "文件名不是excel格式";
            return false;
        }
        return true;
    }

    /**
     * @描述:根据文件名读取excel文件
     */
    public List<List<String>> read(String filePath){
        List<List<String>> dataLst = new ArrayList<List<String>>();
        InputStream is = null;
        try{
            /** 验证文件是否合法 */
            if (!validateExcel(filePath)){
                return null;
            }
            /** 判断文件的类型,是2003还是2007 */
            boolean isExcel2003 = true;
            if (CEVUtil.isExcel2007(filePath)){
                isExcel2003 = false;
            }
            /** 调用本类提供的根据流读取的方法 */
            is = new FileInputStream(new File(filePath));
            Workbook wb = null;
            if (isExcel2003){
                wb = new HSSFWorkbook(is);
            }else{
                wb = new XSSFWorkbook(is);
            }
            dataLst = read(wb);
            is.close();
        }catch (IOException e){
            e.printStackTrace();
        }catch (Exception ex){
            ex.printStackTrace();
        }finally{
            if (is != null){
                try{
                    is.close();
                }catch (IOException e){
                    is = null;
                    e.printStackTrace();
                }
            }
        }
        return dataLst;
    }

    /**
     * @描述:读取数据
     */
    private List<List<String>> read(Workbook wb){
        List<List<String>> dataLst = new ArrayList<List<String>>();
        /**得到总的shell */
        int sheetAccount = wb.getNumberOfSheets();
        /** 得到第一个shell(第一页) */
        Sheet sheet = wb.getSheetAt(0);
        /** 得到Excel的行数 */
        int rowCount = sheet.getPhysicalNumberOfRows();
        /** 也可以通过得到最后一行数*/
        int lastRowNum = sheet.getLastRowNum();
        /** 循环Excel的行 */
        for (int r = 0; r < rowCount; r++){
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            List<String> rowLst = new ArrayList<String>();
            /** 循环Excel的列 */
            for (int c = 0; c < row.getPhysicalNumberOfCells(); c++){
                Cell cell = row.getCell(c);
                String cellValue = "";
                if (null != cell){
                    // 以下是判断数据的类型
                    switch (cell.getCellType()){
                        //XSSFCell可以达到相同的效果
                        case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                            double d = cell.getNumericCellValue();
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {//日期类型
                                // Date date = cell.getDateCellValue();
                                Date date = HSSFDateUtil.getJavaDate(d);
                                cellValue =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
                            }else{//数值类型
                                cellValue = cell.getNumericCellValue()+"";
                            }
                            cellValue = cell.getDateCellValue() + "";
                            break;
                        case HSSFCell.CELL_TYPE_STRING: // 字符串
                            cellValue = cell.getStringCellValue();
                            break;
                        case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                            cellValue = cell.getBooleanCellValue() + "";
                            break;
                        case HSSFCell.CELL_TYPE_FORMULA: // 公式
                            cellValue = cell.getCellFormula() + "";
                            break;
                        case HSSFCell.CELL_TYPE_BLANK: // 空值
                            cellValue = "";
                            break;
                        case HSSFCell.CELL_TYPE_ERROR: // 故障
                            cellValue = "非法字符";
                            break;
                        default:
                            cellValue = "未知类型";
                            break;
                    }
                }
                System.out.print(cellValue +"\t");
                rowLst.add(cellValue);
            }
            System.out.println();
            dataLst.add(rowLst);
        }
        return dataLst;
    }



// -----------------------------------向excel写入数据

    // 标题字体
    private HSSFFont titleFont = null;
    // private XSSFFont titleFont = null; //2007格式


    // 标题样式
    private HSSFCellStyle titleStyle = null;
    // private XSSFCellStyle titleStyle = null;//2007格式

    // 行信息内容样式
    private HSSFCellStyle contentStyle = null;
    // private XSSFCellStyle contentStyle = null;//2007格式

    /** 写excel文件
     * @throws IOException
     */
    public void writeExcel(String[] titleStrs,List<String[]> contentList,String filename) throws IOException{
        FileOutputStream fileOut = new FileOutputStream("C:\\Users\\javaloveiphone\\Desktop\\example.xls");
        /*
        * severlet响应生成excel文件
        * HttpServletResponse response
        *
        * // 文件标题
        *  String head = new String(filename.getBytes("GB2312"), "ISO-8859-1");
        * response.reset();
        * response.setContentType("application/vnd.ms-excel");
        * response.addHeader("Content-Disposition", "attachment; filename="+ head + ".xls");
        *
        *  HSSFWorkbook wb = new HSSFWorkbook();
        *  。。。。。
        *
        *  java.io.OutputStream os = response.getOutputStream();
        *  wb.write(os);
        *  os.close();
        *
        */

        HSSFWorkbook wb = new HSSFWorkbook();// 创建新HSSFWorkbook对象
        // XSSFWorkbook wb = new XSSFWorkbook();//2007格式

        setExcelStyle(wb);//执行样式初始化

        HSSFSheet sheet = wb.createSheet(filename);// 创建新的sheet对象
        // XSSFSheet sheet = wb.createSheet(filename);//2007格式

        HSSFRow titleRow = sheet.createRow((short) 0);//创建第一行
        // XSSFRow titleRow = sheet.createRow((short) 0);//2007格式

        // titleRow.setHeight((short)300);//设置行高,设置太小可能被隐藏看不到
        titleRow.setHeightInPoints(20);//20像素
        int titleCount = titleStrs.length;// 列数
        // 写标题
        for (int k = 0; k < titleCount; k++) {
            HSSFCell cell = titleRow.createCell((short) k); // 新建一个单元格
            // XSSFCell cell = titleRow.createCell((short) k); //2007格式

            // cell.setEncoding(HSSFCell.ENCODING_UTF_16); // 中文字符集转换
            cell.setCellStyle(titleStyle);//设置标题样式
            // cell.setCellValue(new HSSFRichTextString(titleStrs[k])); // 为单元格赋值
            // cell.setCellValue(wb.getCreationHelper().createRichTextString(""));
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(titleStrs[k]);
            sheet.setColumnWidth((short)k, (short)5000);//设置列宽
        }

        int contentCount = contentList.size();//总的记录数
        // 写内容
        for (int i = 0; i < contentCount; i++) {
            String [] contents = contentList.get(i);
            HSSFRow row = sheet.createRow((short)(i + 1)); // 新建一行
            // XSSFRow row = sheet.createRow((short)(i + 1)); // //2007格式

            for (int j = 0; j < titleCount; j++) {
                HSSFCell cell = row.createCell((short) j); // 新建一个单元格
                // XSSFCell cell = row.createCell((short) j); // //2007格式

                cell.setCellStyle(contentStyle);//设置内容样式
                if (contents[j] == null || contents[j].equals("null")) {
                    contents[j] = "";
                }
                //格式化日期
                if(j == 2){
                    HSSFCellStyle style = wb.createCellStyle();
                    // XSSFCellStyle style = wb.createCellStyle();//2007格式
                    style.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
                    // cell.setCellValue(new Date());
                    // cell.setCellValue(Calendar.getInstance());
                    cell.setCellValue(contents[j]);
                    cell.setCellStyle(style);
                }else{
                    cell.setCellValue(new HSSFRichTextString(contents[j]));
                }
            }
        }
        wb.write(fileOut);
        fileOut.flush();
        fileOut.close();
    }
    /** 样式初始化*/
    public void setExcelStyle(HSSFWorkbook workBook){
        // 设置列标题字体,样式
        titleFont = workBook.createFont();
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 标题列样式
        titleStyle = workBook.createCellStyle();
        titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); // 设置边框
        titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleStyle.setFont(titleFont);
        // 内容列样式
        contentStyle = workBook.createCellStyle();
        contentStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        contentStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        contentStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        contentStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        contentStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        contentStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
    }

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在前端中,你可以使用以下方法来实现导入导出 Excel 文件: 1. 导出 Excel 文件: - 使用 Excel.js、xlsx-populate、xlsx-writer 等库来生成 Excel 文件。 - 将数据转换为 Excel 格式并下载到客户端。在浏览器中,你可以创建一个 Blob 对象,然后使用 URL.createObjectURL(blob) 方法来生成下载链接,最后使用 a 标签的 download 属性来触发下载。 2. 导入 Excel 文件: - 使用第三方库如 exceljs、xlsx、xlsx-populate 等来读取和解析 Excel 文件。 - 通过文件输入(input file)元素让用户选择要上传的 Excel 文件,并使用 FileReader 对象读取文件内容。 - 使用解析库将读取到的数据进行处理,如解析为 JSON 或者直接处理为 JavaScript 对象。 以下是一个使用 SheetJS/xlsx 库导入导出 Excel 文件的示例: ```html <!-- 导入 Excel 文件 --> <input type="file" id="file-input" accept=".xlsx,.xls" /> <!-- 导出 Excel 按钮 --> <button id="export-btn">导出 Excel</button> <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script> <script> // 导入 Excel 文件 document.getElementById('file-input').addEventListener('change', function(event) { var file = event.target.files[0]; var reader = new FileReader(); reader.onload = function(e) { var data = new Uint8Array(e.target.result); var workbook = XLSX.read(data, { type: 'array' }); // 处理 Excel 数据 var sheetName = workbook.SheetNames[0]; var worksheet = workbook.Sheets[sheetName]; var jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); console.log(jsonData); }; reader.readAsArrayBuffer(file); }); // 导出 Excel 文件 document.getElementById('export-btn').addEventListener('click', function() { var worksheet = XLSX.utils.json_to_sheet([ { Name: 'John Doe', Age: 30 }, { Name: 'Jane Smith', Age: 25 } ]); var workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1'); var excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' }); var blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); var url = URL.createObjectURL(blob); var a = document.createElement('a'); a.href = url; a.download = 'data.xlsx'; a.click(); URL.revokeObjectURL(url); }); </script> ``` 这是一个基本的示例,你可以根据需求进行修改和扩展。记得在实际使用中引入相应的库文件,并根据实际情况进行数据处理和样式设置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值