原因:我们经常会遇到甲方给数据是excel格式的数据,当然Navicat是支持导入excel的但是遇到客户想要自己上传Excel入库数据就要手动进行写代码了
一:解析Excel入库
/**
*
* @param request
* @param response
* @param 上传excel文件读取excel数据并保存
*
* @return
* @throws IOException
*/
@RequestMapping(value = "batchUploadExcel")
public void batchUploadExcel(HttpServletRequest req, @RequestParam("file") MultipartFile multipartFile,Model model) throws Exception {
// String name ="C:\\Users\\lenovo\\Desktop\\WGS\\20211026043847.xlsx";
// InputStream multipartFile = new FileInputStream(name);
XSSFWorkbook workbook = new XSSFWorkbook(multipartFile.getInputStream());
//获取文本的sheet
XSSFSheet sheet = workbook.getSheetAt(0);
//获取sheet里所有的行数
int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
XSSFRow row;
int count = 0;
String msg ;
for(int i =1; i< physicalNumberOfRows; i++){
row = sheet.getRow(i);
//获取到每行的表格call
// int physicalNumberOfCells = row.getPhysicalNumberOfCells();
// System.out.println("physicalNumberOfCells:"+physicalNumberOfCells);
row.getCell(i).setCellType(Cell.CELL_TYPE_STRING); //设置单元格格式
row.getCell(i).getStringCellValue() //获取单元格 内容
row.getCell(i).getDateCellValue(); //获取单元格日期类型 (更多去查看api)
}
}
二:java列表数据生成Excel文档
@RequestMapping(value="test")
public void text(HttpServletRequest request{
// 创建excel
Workbook excel = new XSSFWorkbook();
// 标题行抽出字段
String[] title = { "列1", "列2","列3" };
// 设置sheet名称,并创建新的sheet对象
String sheetName = "需求列表";
Sheet stuSheet = excel.createSheet(sheetName);
// 获取表头行
Row titleRow = stuSheet.createRow(0);
// 创建单元格,设置style居中,字体,单元格大小等
CellStyle style = excel.createCellStyle();
Cell cell = null;
// 把已经写好的标题行写入excel文件中
for (int i = 0; i < title.length; i++) {
cell = titleRow.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
// 把从数据库中取得的数据一一写入excel文件中
arr 代表 查出的 要写入excel的值
Row row = null;
for (int i = 0; i < arr.size(); i++) {
// 创建list.size()行数据
row = stuSheet.createRow(i + 1);
// 把值一一写进单元格里
// 设置第一列为自动递增的序号
row.createCell(0).setCellValue(i + 1);
row.createCell(1).setCellValue(arr.get(i).getname());
row.createCell(2).setCellValue(arr.get(i).getsex());
}
for (int i = 0; i < title.length; i++) {
stuSheet.autoSizeColumn(i, true);
stuSheet.setColumnWidth(i, stuSheet.getColumnWidth(i) * 15 / 10);
}
// 创建文件目录
//UUID uufileid = UUID.randomUUID();
//String fileNamefirst = uufileid.toString();
String dir = uploadconfig.getServerPath();
//String folderPath1 = dir + "/" + fileNamefirst;
// 设置文件名
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddhhmmss");
String fileName = sdf1.format(new Date()) + ".xlsx";
// System.out.println(savePath);
OutputStream fileOut = new FileOutputStream(dir+"/"+fileName);
excel.write(fileOut);
fileOut.close();
}