poi导入

一:Excel导入 HSSFWorkbook excel的文档对象 HSSFSheet excel的表单 HSSFRow excel的行 HSSFCell excel的格子单元 HSSFFont excel字体 HSSFDataFormat 日期格式 在poi1.7中才有以下2项: HSSFHeader sheet头 HSSFFooter sheet尾(只有打印的时候才能看到效果) 和这个样式 HSSFCellStyle cell样式 辅助操作包括 HSSFDateUtil 日期 HSSFPrintSetup 打印 HSSFErrorConstants 错误信息表

二:需要导入的jar包:

     <dependency>
           <groupId>org.apache.poi</groupId>
           <artifactId>poi</artifactId>
           <version>3.14</version>
      </dependency>
      <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
      <dependency>
           <groupId>org.apache.poi</groupId>
           <artifactId>poi-scratchpad</artifactId>
           <version>3.14</version>
           <type>jar</type>
      </dependency>
      <dependency>
           <groupId>org.apache.poi</groupId>
           <artifactId>poi-ooxml</artifactId>
           <version>3.14</version>
           <type>jar</type>
      </dependency>
      <dependency>
           <groupId>org.apache.poi</groupId>
           <artifactId>poi-ooxml-schemas</artifactId>
           <version>3.14</version>
           <type>jar</type>
      </dependency>

二:报表导入的代码

public static testPoiExcel2007(String strPath){ // 构造 XSSFWorkbook 对象,strPath 传入文件路径
// XSSFWorkbook xwb = new XSSFWorkbook(strPath); //兼容2003与2007版的Excel Workbook xssfWorkbook = null;
if ("xls".equals(suffix)) {
xssfWorkbook = new HSSFWorkbook(strPath);
} else if ("xlsx".equals(suffix)) {
xssfWorkbook = new XSSFWorkbook(strPath);
} // 读取第一章表格内容
XSSFSheet sheet = xwb.getSheetAt(0);
// 定义 row、cell
XSSFRow row; String cell;
// 循环输出表格中的内容
for (int i = sheet.getFirstRowNum(); i < sheet.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
for (int j = row.getFirstCellNum(); j < row.getPhysicalNumberOfCells(); j++) {
// 通过 row.getCell(j).toString() 获取单元格内容,
cell = row.getCell(j).toString();
System.out.print(cell + "\t");
}
System.out.println(""); }
}

三:测试:

public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SS");
TimeZone t = sdf.getTimeZone();
t.setRawOffset(0); sdf.setTimeZone(t);
Long startTime = System.currentTimeMillis();
String fileName = "F:\我的文档\学生缴费代码.xlsx”;
// 检测代码
try {
// 读取excel2007
testPoiExcel2007(fileName);
} catch (Exception ex) {
Logger.getLogger(FastexcelReadExcel.class.getName()).log(Level.SEVERE, null, ex);
}
Long endTime = System.currentTimeMillis();
System.out.println("用时:" + sdf.format(new Date(endTime - startTime))); }

四:springmvc + angularjs 实现Excel导入

1:配置 springboot: @Bean

public MultipartResolver multipartResolver() { StandardServletMultipartResolver resolver = new StandardServletMultipartResolver(); resolver.setResolveLazily(true); return resolver; }

2:angularjs:使用ng-file-upload上传文件 参考地址:https://github.com/danialfarid/ng-file-upload

<script src="JS/ng-file-upload.min.js"></script>

<script src="JS/ng-file-upload-shim.min.js"></script>
<script>
    var app = angular.module('app', ['ngFileUpload']);
    app.controller('FileController', function ($scope, Upload) {
        $scope.uploadImg = '';
        //提交
        $scope.submit = function () {
            $scope.upload($scope.file);
        };
        $scope.upload = function (file) {
            $scope.fileInfo = file;
            Upload.upload({
                //服务端接收
                url: '/calendar/batchCreateCalendarEvent?categoryId=' + categoryId,
                //上传的同时带的参数
                data: { 'username': $scope.username },
                file: file
            }).progress(function (evt) {
                //进度条
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progess:' + progressPercentage + '%' + evt.config.file.name);
            }).success(function (data, status, headers, config) {
                //上传成功
                console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
                $scope.uploadImg = data;
            }).error(function (data, status, headers, config) {
                //上传失败
                console.log('error status: ' + status);
            });
        };
    });
</script>

在开发本功能时,由于采用的版本比较老,所以在使用上和最新的用法会不一样,在开发时造成上传不成功,请注意。

3:controller:

public ResponseBean batchCreateCalendarEvent(MultipartFile file ,Long categoryId) { try { //将MultipartFile转换成 File XSSFWorkbook xwb = new XSSFWorkbook(convert(file)); // 读取第一章表格内容 XSSFSheet sheet = xwb.getSheetAt(0); // 定义 row、cell XSSFRow row; Cell cell; CalendarEventEntity calendarEvent; // 循环输出表格中的内容 for (int i = sheet.getFirstRowNum() + 1; i < sheet.getPhysicalNumberOfRows(); i++) { row = sheet.getRow(i); for (int j = row.getFirstCellNum(); j < row.getPhysicalNumberOfCells(); j++) { cell = row.getCell(j); // 获取Excel的时间格式,将其转换成指定的格式 parseExcel(cell); } } catch (Exception e) { e.printStackTrace(); } }

//文件的转换

public File convert(MultipartFile file) throws IOException { File convFile = new File(file.getOriginalFilename()); convFile.createNewFile(); FileOutputStream fos = new FileOutputStream(convFile); fos.write(file.getBytes()); fos.close(); return convFile; }

//获取日期格式 参考链接:http://yl-fighting.iteye.com/blog/1726285 Excel存储日期、时间均以数值类型进行存储,读取时POI先判断是是否是数值类型,再进行判断转化

1、数值格式(CELL_TYPE_NUMERIC):

1.纯数值格式:getNumericCellValue() 直接获取数据

2.日期格式:处理yyyy-MM-dd, d/m/yyyy h:mm, HH:mm 等不含文字的日期格式

1).判断是否是日期格式:HSSFDateUtil.isCellDateFormatted(cell)

2).判断是日期或者时间

cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")

OR: cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("yyyy-MM-dd")

3.自定义日期格式:处理yyyy年m月d日,h时mm分,yyyy年m月等含文字的日期格式

判断cell.getCellStyle().getDataFormat()值,解析数值格式

yyyy年m月d日----->31

m月d日---->58

h时mm分--->32

private String parseExcel(Cell cell) { String result = new String(); switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC:// 数字类型 if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式 SimpleDateFormat sdf = null; if (cell.getCellStyle().getDataFormat() == HSSFDataFormat .getBuiltinFormat("h:mm")) { sdf = new SimpleDateFormat("HH:mm"); } else {// 日期 sdf = new SimpleDateFormat("yyyy-MM-dd"); } Date date = cell.getDateCellValue(); result = sdf.format(date); } else if (cell.getCellStyle().getDataFormat() == 58) { // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); double value = cell.getNumericCellValue(); Date date = org.apache.poi.ss.usermodel.DateUtil .getJavaDate(value); result = sdf.format(date); } else { double value = cell.getNumericCellValue(); CellStyle style = cell.getCellStyle(); DecimalFormat format = new DecimalFormat(); String temp = style.getDataFormatString(); // 单元格设置成常规 if (temp.equals("General")) { format.applyPattern("#"); } result = format.format(value); } break; case HSSFCell.CELL_TYPE_STRING:// String类型 result = cell.getRichStringCellValue().toString(); break; case HSSFCell.CELL_TYPE_BLANK: result = ""; default: result = ""; break; } return result; }

转载于:https://my.oschina.net/u/1422694/blog/846369

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值