大家好,又见面了,我是你们的朋友全栈君。
分享一个朋友的人工智能教程(请以“右键”->”在新标签页中打开连接”的方式访问)。比较通俗易懂,风趣幽默,感兴趣的朋友可以去看看。
开发中经常会设计到excel的处理,如导出Excel,导入Excel到数据库中,操作Excel目前有两个框架,一个是apache 的poi, 另一个是 Java Excel
由于apache poi 在项目中用的比较多,本篇博客只讲解apache poi,不讲jxl
在开发中我们经常使用HSSF用来操作Excel处理表格数据,对于其它的不经常使用。
HSSF 是Horrible SpreadSheet Format的缩写,通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。HSSF 为读取操作提供了两类API:usermodel和eventusermodel,即“用户模型”和“事件-用户模型”。
Excel中的工作簿、工作表、行、单元格中的关系:
一个Excel文件对应于一个workbook(HSSFWorkbook),
一个workbook可以有多个sheet(HSSFSheet)组成,
一个sheet是由多个row(HSSFRow)组成,
一个row是由多个cell(HSSFCell)组成
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
public static void createExcel() throws IOException{
// 获取桌面路径
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
String filePath = desktop + "/template.xls";
File file = new File(filePath);
OutputStream outputStream = new FileOutputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
HSSFRow row = sheet.createRow(0);
row.createCell(0).setCellValue("id");
row.createCell(1).setCellValue("订单号");
row.createCell(2).setCellValue("下单时间");
row.createCell(3).setCellValue("个数");
row.createCell(4).setCellValue("单价");
row.createCell(5).setCellValue("订单金额");
row.setHeightInPoints(30); // 设置行的高度
HSSFRow row1 = sheet.createRow(1);
row1.createCell(0).setCellValue("1");
row1.createCell(1).setCellValue("NO00001");
// 日期格式化
HSSFCellStyle cellStyle2 = workbook.createCellStyle();
HSSFCreationHelper creationHelper = workbook.getCreationHelper();
cellStyle2.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
sheet.setColumnWidth(2, 20 * 256); // 设置列的宽度
HSSFCell cell2 = row1.createCell(2);
cell2.setCellStyle(cellStyle2);
cell2.setCellValue(new Date());
row1.createCell(3).setCellValue(2);
// 保留两位小数
HSSFCellStyle cellStyle3 = workbook.createCellStyle();
cellStyle3.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
HSSFCell cell4 = row1.createCell(4);
cell4.setCellStyle(cellStyle3);
cell4.setCellValue(29.5);
// 货币格式化
HSSFCellStyle cellStyle4 = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setFontName("华文行楷");
font.setFontHeightInPoints((short)15);
font.setColor(HSSFColor.RED.index);
cellStyle4.setFont(font);
HSSFCell cell5 = row1.createCell(5);
cell5.setCellFormula("D2*E2"); // 设置计算公式
// 获取计算公式的值
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook);
cell5 = e.evaluateInCell(cell5);
System.out.println(cell5.getNumericCellValue());
workbook.setActiveSheet(0);
workbook.write(outputStream);
outputStream.close();
}
public static void readExcel() throws IOException{
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
String filePath = desktop + "/template.xls";
FileInputStream fileInputStream = new FileInputStream(filePath);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
HSSFSheet sheet = workbook.getSheet("Sheet1");
int lastRowIndex = sheet.getLastRowNum();
System.out.println(lastRowIndex);
for (int i = 0; i <= lastRowIndex; i++) {
HSSFRow row = sheet.getRow(i);
if (row == null) {
break; }
short lastCellNum = row.getLastCellNum();
for (int j = 0; j < lastCellNum; j++) {
String cellValue = row.getCell(j).getStringCellValue();
System.out.println(cellValue);
}
}
bufferedInputStream.close();
}
@SuppressWarnings("resource")
@RequestMapping("/export")
public void exportExcel(HttpServletResponse response, HttpSession session, String name) throws Exception {
String[] tableHeaders = {
"id", "姓名", "年龄"};
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
Font font = workbook.createFont();
font.setColor(HSSFColor.RED.index);
font.setBold(true);
cellStyle.setFont(font);
// 将第一行的三个单元格给合并
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
HSSFRow row = sheet.createRow(0);
HSSFCell beginCell = row.createCell(0);
beginCell.setCellValue("通讯录");
beginCell.setCellStyle(cellStyle);
row = sheet.createRow(1);
// 创建表头
for (int i = 0; i < tableHeaders.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(tableHeaders[i]);
cell.setCellStyle(cellStyle);
}
List<User> users = new ArrayList<>();
users.add(new User(1L, "张三", 20));
users.add(new User(2L, "李四", 21));
users.add(new User(3L, "王五", 22));
for (int i = 0; i < users.size(); i++) {
row = sheet.createRow(i + 2);
User user = users.get(i);
row.createCell(0).setCellValue(user.getId());
row.createCell(1).setCellValue(user.getName());
row.createCell(2).setCellValue(user.getAge());
}
OutputStream outputStream = response.getOutputStream();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=template.xls");
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
1、使用SpringMVC上传文件,需要用到commons-fileupload
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
2、需要在spring的配置文件中配置一下multipartResolver
<bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
</bean>
3、index.jsp
<a href="/Spring-Mybatis-Druid/user/export">导出</a> <br/>
<form action="/Spring-Mybatis-Druid/user/import" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit" value="导入Excel">
</form>
4、解析上传的.xls文件
@SuppressWarnings("resource")
@RequestMapping("/import")
public void importExcel(@RequestParam("file") MultipartFile file) throws Exception{
InputStream inputStream = file.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
//HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
HSSFSheet sheet = workbook.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
for (int i = 2; i <= lastRowNum; i++) {
HSSFRow row = sheet.getRow(i);
int id = (int) row.getCell(0).getNumericCellValue();
String name = row.getCell(1).getStringCellValue();
int age = (int) row.getCell(2).getNumericCellValue();
System.out.println(id + "-" + name + "-" + age);
}
}
导出效果:
导入效果:
项目示例代码下载地址:
http://download.csdn.net/detail/vbirdbest/9861536
http://www.cnblogs.com/Damon-Luo/p/5919656.html
http://www.cnblogs.com/LiZhiW/p/4313789.html
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/154124.html原文链接:https://javaforall.cn