Java使用POI操作Excel表格上传下载
程序员文章站
2022-07-14 16:59:43
...
Java使用POI操作Excel表格上传下载
最近项目要求有文件上传下载功能,写篇日记记录一下,主要记录四点:
- 导包:
- 上传:
- 下载:
- 解析Excel表
1、导包:(已打包好,内附说明图)
https://download.csdn.net/download/weixin_43119338/10642220
2、上传:
-
form表单直接上传到servlet
首先将文件上传到服务器,使用apache提供的
FileUtils.copyInputeStreanToFile(inputstrean,file)来上传。可参考如下代码:
第一步:
// 文件上传路径
String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE;
// 执行上传(file:上传的文件,filePath:文件上传路径,xxxexcel:生成的文件名)
String fileName = FileUpload.fileUp(file, filePath, "xxxexcel");
第二步:
public static String fileUp(MultipartFile file, String filePath, String fileName){
String extName = ""; // 扩展名格式:
try {
if (file.getOriginalFilename().lastIndexOf(".") >= 0){
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}
copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
} catch (IOException e) {
System.out.println(e);
}
return fileName+extName;
}
第三步:
private static String copyFile(InputStream in, String dir, String realName)
throws IOException {
File file = new File(dir, realName);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
FileUtils.copyInputStreamToFile(in, file); //真正执行上传的方法
return realName;
}
3、下载:
主要代码如下
public class ObjectExcelView extends AbstractExcelView {
@Override
protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Date date = new Date();
String filename = Tools.date2Str(date, "yyyyMMddHHmmss");//设置生成的文件名
HSSFSheet sheet;
HSSFCell cell;
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xls"); //设置响应头
sheet = workbook.createSheet("sheet1");
List<String> titles = (List<String>) model.get("titles");//获取查询出来的数据
int len = titles.size();
HSSFCellStyle headerStyle = workbook.createCellStyle(); //标题样式
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
HSSFFont headerFont = workbook.createFont();// 标题字体
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerFont.setFontHeightInPoints((short) 11);
headerStyle.setFont(headerFont);
short width = 20, height = 25 * 20;
sheet.setDefaultColumnWidth(width);
for (int i = 0; i < len; i++) { // 设置标题样式
String title = titles.get(i);
cell = getCell(sheet, 0, i);
cell.setCellStyle(headerStyle);
setText(cell, title);
}
sheet.getRow(0).setHeight(height);
HSSFCellStyle contentStyle = workbook.createCellStyle();// 设置内容样式
contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
contentStyle.setFillBackgroundColor(HSSFColor.WHITE.index);
contentStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
contentStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
List<PageData> varList = (List<PageData>) model.get("varList");
int varCount = varList.size();
for (int i = 0; i < varCount; i++) {
PageData vpd = varList.get(i);
for (int j = 0; j < len; j++) {
String varstr = vpd.getString("var" + (j + 1)) != null ? vpd.getString("var" + (j + 1)) : "";
cell = getCell(sheet, i + 1, j);
cell.setCellStyle(contentStyle);
setText(cell, varstr);
}
}
}
}
4、解析Excel表:
/**
* @param filepath //文件路径
* @param filename //文件名
* @param startrow //开始行号
* @param startcol //开始列号
* @param sheetnum //第几个sheet
* @return list
*/
public static List<Object> readExcel(String filepath, String filename, int startrow, int startcol, int sheetnum) {
List<Object> varList = new ArrayList<Object>();
try {
File target = new File(filepath, filename);
FileInputStream fi = new FileInputStream(target);
Workbook wb = WorkbookFactory.create(fi);
Sheet sheet = wb.getSheetAt(sheetnum); //第几个sheet,一般从0开始
ridNullRow(sheet); //加一个方法,用来去除excel表里的空行
int rowNum = sheet.getLastRowNum() + 1; //取得最后一行的行号
for (int i = startrow; i < rowNum; i++) { //行循环开始
Map map = new HashedMap();
Row row = sheet.getRow(i);
int cellNum = row.getLastCellNum(); //每行的最后一个单元格位置
for (int j = startcol; j < cellNum; j++) { //列循环开始
Cell cell = row.getCell(j);
String result = null;
if (null != cell) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
result = cell.getBooleanCellValue() + "";
break;
case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
result = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
// 可能是普通数字,也可能是日期
if (HSSFDateUtil.isCellDateFormatted(cell)) {
result = DateUtil.getJavaDate(cell.getNumericCellValue()).toString();
} else {
result = cell.getNumericCellValue() + "";
}
break;
}
} else {
result = "";
}
map.put("var"+j, result); //自定义一个字段,存放每一行里的各单元格的值
}
varList.add(map); //每一行的数据再放到一个集合里
}
} catch (Exception e) {
System.out.println(e);
}
return varList; //返回数据集合
}
/**
* 去除Excel表中的空行
*/
private static void ridNullRow(Sheet sheet) {
CellReference cellReference = new CellReference("A4");
boolean flag = false;
for (int i = cellReference.getRow() - 1; i <= sheet.getLastRowNum();) {
Row r = sheet.getRow(i);
if (r == null) {
// 如果是空行(即没有任何数据、格式),直接把它以下的数据往上移动
sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
continue;
}
flag = false;
for (Cell c : r) {
if (c.getCellType() != Cell.CELL_TYPE_BLANK) {
flag = true;
break;
}
}
if (flag) {
i++;
continue;
} else {// 如果是空白行(即可能没有数据,但是有一定格式)
if (i == sheet.getLastRowNum())// 如果到了最后一行,直接将那一行remove掉
sheet.removeRow(r);
else// 如果还没到最后一行,则数据往上移一行
sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
}
}
}
上一篇: 1.13 Java之XML解析
下一篇: Java解析Properties.xml