java控制excel_java操作excel

本文介绍了如何使用Java操作Excel。首先展示了如何生成并下载Excel文件,通过创建`Workbook`,设置工作表和表头,然后将内容写入单元格。接着,详细解释了如何解析前端上传的Excel,包括读取文件,处理每个单元格的数据,以及根据单元格类型转换值。
摘要由CSDN通过智能技术生成

1. 生成并下载excel文件

controller

@RequestMapping(value = "/download", method = RequestMethod.GET)

public xxx downloadFile(HttpServletResponse response) {

response.setContentType("application/octet-stream");

response.setHeader("content-type", "application/octet-stream");

try {

response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "UTF-8"));// 设置文件名

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

try {

excelService.download(response.getOutputStream());

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

service

public interface ExcelService {

void download(OutputStream outputStream) throws IOException;

}

impl

@Override

public void download(OutputStream outputStream) throws IOException{

//1.创建excel(工作簿)

Workbook wb = new XSSFWorkbook();

//2.创建Sheet

Sheet sheet = wb.createSheet();

//3.创建表头,参数为要创建的行的位置

Row header = sheet.createRow(0);

//4.创建单元格对象,向单元格写数据

Cell cell = null;

List headerList = Lists.newArrayList("姓名","年龄","性别","爱好","生日");

for (int i = 0; i < headerList.size(); i++) {

//行对象.createCell(单元格位置)

cell = header.createCell(i);

//赋值

cell.setCellValue(headerList.get(i));

}

//5.工作簿写进输出流

wb.write(outputStream);

}

2. 解析前端上传的excel

Controller

@RequestMapping(value = "/excel/import", method = RequestMethod.GET)

public xxx uploadExcel(@RequestParam("upload") MultipartFile file) {

excelService.uploadExcel(file);

return xxx.OK;

}

service

public interface ExcelService {

void uploadExcel(MultipartFile multipartFile);

}

impl

public void uploadExcel(MultipartFile multipartFile) {

List dataList = ExcelUtil.loadExcelData(multipartFile);

}

ExcelUtil

public static List loadExcelData(MultipartFile file) throws Exception {

Workbook wb;// 创建Excel2003文件对象

wb = WorkbookFactory.create(file.getInputStream());

//获取第一个页签对象

Sheet sheet = wb.getSheetAt(0);

//获取有内容的总行数

int rowsNumber = sheet.getLastRowNum();

if (rowsNumber >= 0) {

List excelList = new ArrayList<>(rowsNumber);

//遍历页签的每一行

Row firstRow = sheet.getRow(0);

if (rowsNumber == 0 && firstRow == null) {

return null;

}

//总列数

int cellsNumber = sheet.getRow(0).getLastCellNum();

for (int i = 0; i <= rowsNumber; i++) {

Row row = sheet.getRow(i);// 获取行对象

if (row == null) {// 如果为空,不处理

continue;

}

int num = 0;//记录该行的空格总数

List newList = new ArrayList<>(cellsNumber);

for (int j = 0; j < cellsNumber; j++) {

Cell cell = row.getCell(j);// 获取单元格对象

if (cell != null) {

String value = getValueByType(cell);

if (StringUtils.isEmpty(value)) {

num += 1;

}

newList.add(value);

} else {

newList.add("");

num += 1;

}

}

if (num < cellsNumber) {//不是全部空格,把这行加到返回数据中

excelList.add(newList);

}

}

return excelList;

}

wb.close();

return null;

}

private static String getValueByType(Cell cell) {

//判断是否为null或空串

if (cell==null || cell.toString().trim().equals("")) {

return "";

}

String cellValue = "";

int cellType=cell.getCellType();

if(cellType==Cell.CELL_TYPE_FORMULA){ //表达式类型

cellType=evaluator.evaluate(cell).getCellType();

}

switch (cellType) {

case Cell.CELL_TYPE_STRING: //字符串类型

cellValue= cell.getStringCellValue().trim();

cellValue=StringUtils.isEmpty(cellValue) ? "" : cellValue;

break;

case Cell.CELL_TYPE_BOOLEAN: //布尔类型

cellValue = String.valueOf(cell.getBooleanCellValue());

break;

case Cell.CELL_TYPE_NUMERIC: //数值类型

if (HSSFDateUtil.isCellDateFormatted(cell)) { //判断日期类型

cellValue = DateUtil.formatDateByFormat(cell.getDateCellValue(), "yyyy-MM-dd");

} else { //否

cellValue = new DecimalFormat("#.######").format(cell.getNumericCellValue());

}

break;

default: //其它类型,取空串吧

cellValue = "";

break;

}

return cellValue;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值