1.HSSFWorkbook(xls)

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; /*读取xls文件*/
public static List<PageData> readExcelByFileForXls(File file, int startrow, int startcol, int sheetnum) {
List<PageData> varList = new ArrayList<PageData>(); try {
//File target = new File(filepath, filename);
//File target = new File(file);
FileInputStream fi = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(fi);//xslx
HSSFSheet sheet= wb.getSheetAt(sheetnum); //sheet 从0开始 int rowNum = sheet.getLastRowNum() + 1; //取得最后一行的行号 for (int i = startrow; i < rowNum; i++) { //行循环开始 PageData varpd = new PageData();
HSSFRow row = sheet.getRow(i); //行
int cellNum = row.getLastCellNum(); //每行的最后一个单元格位置 for (int j = startcol; j < cellNum; j++) { //列循环开始 HSSFCell cell = row.getCell(Short.parseShort(j + ""));
String cellValue = null;
if (null != cell) {
switch (cell.getCellType()) { // 判断excel单元格内容的格式,并对其进行转换,以便插入数据库
case 0:
cellValue = String.valueOf((int) cell.getNumericCellValue());
break;
case 1:
cellValue = cell.getStringCellValue();
break;
case 2:
cellValue = cell.getNumericCellValue() + "";
// cellValue = String.valueOf(cell.getDateCellValue());
break;
case 3:
cellValue = "";
break;
case 4:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case 5:
cellValue = String.valueOf(cell.getErrorCellValue());
break;
}
} else {
cellValue = "";
} varpd.put("var"+j, cellValue); }
varList.add(varpd);
} } catch (Exception e) {
System.out.println(e);
} return varList;
}

2.XSSFWorkbook(xlsx)

/*读取xlsx文件*/
public static List<PageData> readExcelByFileForXlsx(File file, int startrow, int startcol, int sheetnum) {
List<PageData> varList = new ArrayList<PageData>();
try {
//File target = new File(filepath, filename);
//File target = new File(file);
FileInputStream fi = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(fi);//xslx
XSSFSheet sheet= wb.getSheetAt(sheetnum); //sheet 从0开始
int rowNum = sheet.getLastRowNum() + 1; //取得最后一行的行号 for (int i = startrow; i < rowNum; i++) { //行循环开始 PageData varpd = new PageData();
XSSFRow row = sheet.getRow(i); //行
int cellNum = row.getLastCellNum(); //每行的最后一个单元格位置 for (int j = startcol; j < cellNum; j++) { //列循环开始 XSSFCell cell = row.getCell(Short.parseShort(j + ""));
String cellValue = null;
if (null != cell) {
switch (cell.getCellType()) { // 判断excel单元格内容的格式,并对其进行转换,以便插入数据库
case 0:
cellValue = String.valueOf((int) cell.getNumericCellValue());
break;
case 1:
cellValue = cell.getStringCellValue();
break;
case 2:
cellValue = cell.getNumericCellValue() + "";
// cellValue = String.valueOf(cell.getDateCellValue());
break;
case 3:
cellValue = "";
break;
case 4:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case 5:
cellValue = String.valueOf(cell.getErrorCellValue());
break;
}
} else {
cellValue = "";
} varpd.put("var"+j, cellValue); }
varList.add(varpd);
} } catch (Exception e) {
System.out.println(e);
} return varList;
}
poi导出excel最常用的是第一种方式HSSFWorkbook,不过这种方式数据量大的话会产生内存溢出问题,SXSSFWorkbook是一种大数据量导出格式,csv是另一种excel导出的一种轻快的实现。

先介绍一下这三种格式的特点

1 HSSFWorkbook  excel文件底层是txt实现,我们经常见到的excel都是这种实现的。

2 SXSSFWorkbook  excel文件底层是xml实现,同样的数据量,大约是第一种的1/6-1/4之间

3 csv 这个比较新潮,数据量应该更小,可以百度。

一 HSSFWorkbook 实现

Map<String, Object> dataMap = service.AssignMiddleExcel(page);
ObjectExcelView erv = new ObjectExcelView("逾期客户表"); //执行excel操作
mv = new ModelAndView(erv,dataMap);
dataMap 是个map ,包含两个键值对 一个是标题列
Map<String,Object> dataMap = new HashMap<String,Object>();
List<String> titles = new ArrayList<String>(); titles.add("借款人姓名"); //
titles.add("身份证号"); //
titles.add("借款人手机号");
dataMap.put("titles", titles);
这是标题列
vpd是个map
vpd.put("var1", userList.get(i).getString("realName")); //
vpd.put("var2", userList.get(i).getString("contIdCard")); //
vpd.put("var3", userList.get(i).getString("telephone")); //
List<PageData> varList = new ArrayList<PageData>();
PageData就是个HashMap
varList.add(vpd);
dataMap.put("varList", varList);
这就是dataMap的由来 public class ObjectExcelView extends AbstractExcelView{ private String fileName; public ObjectExcelView(){ }
public ObjectExcelView(String fileName){ this.fileName = fileName;
} @Override
protected void buildExcelDocument(Map<String, Object> model,
HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
//String fileName = "逾期客户表-待催收";
HSSFSheet sheet;
HSSFCell cell;
response.setContentType("application/x-download");//下面三行是关键代码,处理乱码问题
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gbk"), "iso8859-1")+".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);
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);
} } } } 二 SXSSFWorkbook
@RequestMapping("/excel111")
public Object exportExcel(Page page,HttpServletRequest request,HttpServletResponse response){
PageData pd = new PageData();
pd = this.getPageData();
try{
//检索条件===========
PageData pageData = service.setPdWithTrim(this.getPageData());
page.setPd(pageData);
//检索条件===========
Map<String, Object> dataMap = service.AssignMiddleExcel(page);
OutputStream outputStream = response.getOutputStream();
String sheetName = "逾期客户表";
List<String> list = (List<String>)dataMap.get("titles");
String[] headers = new String[list.size()];
for(int i = 0;i<list.size();i++){
headers[i]=list.get(i);
}
List<Object[]> dataList = new ArrayList<>();
List<PageData> varList = new ArrayList<PageData>();
varList = (List<PageData>)dataMap.get("varList"); varList.forEach(e ->{
List<Object> ObjectList = new ArrayList<>();
for(int i=0;i<headers.length;i++){
ObjectList.add(e.get("var"+(i+1))==null?null:e.getString("var"+(i+1)));
}
/* for (Object v : e.values()) {
ObjectList.add(v);
}*/
Object[] objarr = new Object[ObjectList.size()];
for(int i = 0;i<ObjectList.size();i++){
objarr[i] = ObjectList.get(i);
}
dataList.add(objarr);
});
ExportUtil exportUtil = new ExportUtil(sheetName,headers,dataList);
//SXSSFWorkbook 大批量数据导出
SXSSFWorkbook workBook = exportUtil.export();
// 如果文件名有中文,必须URL编码
String fileName1 = URLEncoder.encode(sheetName, "UTF-8");
// response.reset();
// response.setContentType("application/force-download");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName1+".xls");
workBook.write(outputStream);
workBook.close();
outputStream.flush();
outputStream.close(); //ObjectExcelView erv = new ObjectExcelView("逾期客户表"); //执行excel操作
//mv = new ModelAndView(erv,dataMap);
} catch(Exception e){
logger.error(e.toString(), e);
}
return new Object();
} package com.fh.controller.assign_out;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.springframework.util.StringUtils;
/**
* Created by dell、 on 2017/10/12.
*/
public class ExportUtil {
private SXSSFWorkbook wb = null;//大数据导出格式 private Sheet sheet = null; private String sheetName; private String[] headers;//表头字段 private List<Object[]> dataList = new ArrayList<Object[]>();//表内容数据
//构造
public ExportUtil(SXSSFWorkbook wb, Sheet sheet) {
this.wb = wb;
this.sheet = sheet;
}
//构造
public ExportUtil(String sheetName, String[] headers, List<Object[]> dataList) {
this.dataList = dataList;
this.headers = headers;
this.sheetName = sheetName;
}
//不知道做什么
public void setRegionStyle(CellRangeAddress region, XSSFCellStyle cs) {
int toprowNum = region.getFirstRow();
for (int i = toprowNum; i <= region.getLastRow(); i++) {
SXSSFRow row = (SXSSFRow) sheet.getRow(i); for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
SXSSFCell cell = (SXSSFCell) row.getCell(j);
cell.setCellStyle(cs);
}
}
} // 设置表头的单元格样式
public CellStyle getHeadStyle() {
// 创建单元格样式
CellStyle cellStyle = wb.createCellStyle();
// 设置单元格的背景颜色为淡蓝色
cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
// 设置填充字体的样式
cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); // 设置单元格居中对齐
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 设置单元格垂直居中对齐
cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 创建单元格内容显示不下时自动换行
cellStyle.setWrapText(false); // 设置单元格字体样式
XSSFFont font = (XSSFFont) wb.createFont();
// font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 这是字体加粗
font.setFontName("宋体");// 设置字体的样式
font.setFontHeight(14);// 设置字体的大小
cellStyle.setFont(font);// 将字体填充到表格中去 // 设置单元格边框为细线条(上下左右)
cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); return cellStyle; } // 设置表体的单元格样式
public CellStyle getBodyStyle() {
// 创建单元格样式
CellStyle cellStyle = wb.createCellStyle();
// 设置单元格居中对齐
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
// 设置单元格居中对齐
cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
// 创建单元格内容不显示自动换行
cellStyle.setWrapText(false);
// 设置单元格字体样式
XSSFFont font = (XSSFFont) wb.createFont();
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 这是字体加粗
font.setFontName("宋体");// 设置字体
font.setFontHeight(12);// 设置字体的大小
cellStyle.setFont(font);// 将字体添加到表格中去 // 设置单元格边框为细线条
cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); return cellStyle; }
//似乎没用到
public Cell setHeadStyle(String[] titles) {
Cell cell = null; CellStyle headStyle = getHeadStyle(); Row headRow = sheet.createRow(0);
// 构建表头
for (int i = 0; i < titles.length; i++) {
cell = headRow.createCell(i);
cell.setCellStyle(headStyle);
cell.setCellValue(titles[i]);
}
return cell;
} /*
* 导出数据
*/
public SXSSFWorkbook export() throws Exception {
// String nsheetName = new String(sheetName.getBytes("UTF-8"));
/*
* response.setCharacterEncoding("utf-8");
* response.setContentType("application/x-msdownload");
* response.setHeader("Content-disposition", "attachment; filename=" +
* sheetName + ".xlsx");// 组装附件名称和格式
*/
Integer rowaccess = 1000;// 内存中缓存记录行数,以免内存溢出 SXSSFWorkbook workbook = new SXSSFWorkbook(rowaccess);
try { Sheet sheet = workbook.createSheet(sheetName); // 产生表格标题行
Row titleRow = sheet.createRow(0);
Cell cellTiltle = titleRow.createCell(0);
CellStyle columnTopStyle = this.getColumnTopStyle(workbook);// 获取列头样式对象
sheet.setDefaultColumnWidth(100);
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (headers.length - 1)));
cellTiltle.setCellStyle(columnTopStyle);
cellTiltle.setCellValue(sheetName); Cell cell = null; CellStyle headStyle = this.getHeadStyle(workbook); // 定义所需列数
int columnNum = headers.length;
Row headRow = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行) //表头
for (int n = 0; n < columnNum; n++) {
Cell cellRowName = headRow.createCell(n); // 创建列头对应个数的单元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
HSSFRichTextString text = new HSSFRichTextString(headers[n]);
cellRowName.setCellValue(headers[n]); // 设置列头单元格的值
cellRowName.setCellStyle(headStyle); // 设置列头单元格样式
sheet.setColumnWidth(n,256*20);
} CellStyle bodyStyle = this.getBodyStyle(workbook); // 表体数据
for (int i = 0; i < dataList.size(); i++) { Object[] obj = dataList.get(i);
Row row = sheet.createRow(i + 3);// 创建所需的行数 for (int j = 0; j < obj.length; j++) { cell = row.createCell(j);
String str = String.valueOf(StringUtils.isEmpty(obj[j]) ? "" : obj[j]);
cell.setCellValue(str); // 单元格的值
cell.setCellStyle(bodyStyle); // 单元格的样式
}
} } catch (Exception e) {
e.printStackTrace();
} return workbook;
} // 设置表头的单元格样式
public CellStyle getHeadStyle(SXSSFWorkbook workbook) {
// 创建单元格样式
CellStyle cellStyle = workbook.createCellStyle(); // 设置单元格的背景颜色为淡蓝色
cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
// 设置填充字体的样式
cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); // 设置单元格居中对齐
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 设置单元格垂直居中对齐
cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
// cellStyle.setShrinkToFit(true);
// 创建单元格内容显示不下时自动换行
//cellStyle.setWrapText(true); // 设置单元格字体样式
XSSFFont font = (XSSFFont) workbook.createFont();
// font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 这是字体加粗
font.setFontName("宋体");// 设置字体的样式
font.setFontHeight(12);// 设置字体的大小
cellStyle.setFont(font);// 将字体填充到表格中去 // 设置单元格边框为细线条(上下左右)
cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); return cellStyle; } // 设置表体的单元格样式
public CellStyle getBodyStyle(SXSSFWorkbook workbook) {
// 创建单元格样式
CellStyle cellStyle = workbook.createCellStyle();
// 设置单元格居中对齐
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
// 设置单元格居中对齐
cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
// 创建单元格内容不显示自动换行
//cellStyle.setWrapText(true);
// 设置单元格字体样式
XSSFFont font = (XSSFFont) workbook.createFont();
// font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 这是字体加粗
font.setFontName("宋体");// 设置字体
font.setFontHeight(10);// 设置字体的大小
cellStyle.setFont(font);// 将字体添加到表格中去 // 设置单元格边框为细线条
cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); return cellStyle; } public Cell setHeadStyle(String[] titles, SXSSFWorkbook workbook) {
Cell cell = null; CellStyle headStyle = getHeadStyle(workbook); Row headRow = sheet.createRow(0);
// 构建表头
for (int i = 0; i < titles.length; i++) {
cell = headRow.createCell(i);
cell.setCellStyle(headStyle);
cell.setCellValue(titles[i]);
}
return cell;
} /*
* 列头单元格样式
*/
public CellStyle getColumnTopStyle(SXSSFWorkbook workbook) { // 设置字体
Font font = workbook.createFont();
// 设置字体大小
font.setFontHeightInPoints((short) 18);
// 字体加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 设置字体名字
font.setFontName("Courier New");
// 设置样式;
CellStyle style = workbook.createCellStyle();
// 设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
// 设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
// 设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// 设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
// 设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
// 设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
// 设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
// 设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
// 在样式用应用设置的字体;
style.setFont(font);
// 设置自动换行;
style.setWrapText(false);
// 设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style; }
} 三 csv
/*
* 导出委外催收中EXCEL 大数据量csv导出
* @return
*/
@RequestMapping("/excel")
public Object exportExcel111(Page page, HttpServletResponse response ) {
PageData pd = new PageData();
pd = this.getPageData();
try {
//检索条件===========
PageData pageData = service.setPdWithTrim(this.getPageData());
page.setPd(pageData);
//检索条件===========
Map<String, Object> dataMap = service.AssignMiddleExcel(page);
String sheetName = "逾期客户表";
List<Object> headlist = (List<Object>)dataMap.get("titles");
List<List<Object>> dataList = new ArrayList<>();
List<PageData> varList = new ArrayList<PageData>();
varList = (List<PageData>)dataMap.get("varList"); varList.forEach(e ->{
List<Object> ObjectList = new ArrayList<>();
for(int i=0;i<headlist.size();i++){
ObjectList.add(e.get("var"+(i+1))==null?null:e.getString("var"+(i+1)));
}
dataList.add(ObjectList);
});
File csvFile =CSVUtils.createCSVFile(headlist,dataList,sheetName);
BufferedInputStream bis = null;
BufferedOutputStream bos = null; response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(csvFile.getName(), "UTF-8")); response.setHeader("Content-Length", String.valueOf(csvFile.length())); bis = new BufferedInputStream(new FileInputStream(csvFile));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
while (true) {
int bytesRead;
if (-1 == (bytesRead = bis.read(buff, 0, buff.length))) break;
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
csvFile.delete();
}catch (Exception e){
e.printStackTrace();
}
return new Object();
}
package com.fh.controller.assign_out; import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*; /**
* Created by dell、 on 2017/10/12.
*/
public class CSVUtils {
/**
* CSV文件生成方法
* @param head
* @param dataList
* @param filename
* @return
*/
public static File createCSVFile(List<Object> head, List<List<Object>> dataList,
String filename) { File csvFile = null;
BufferedWriter csvWtriter = null;
try {
csvFile = new File( "temp123/"+ File.separator + filename + ".csv");
File parent = csvFile.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
csvFile.createNewFile(); // GB2312使正确读取分隔符","
csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
csvFile), "GB2312"), 1024);
// 写入文件头部
writeRow(head, csvWtriter); // 写入文件内容
for (List<Object> row : dataList) {
writeRow(row, csvWtriter);
}
csvWtriter.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
csvWtriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return csvFile;
} /**
* 写一行数据方法
* @param row
* @param csvWriter
* @throws IOException
*/
private static void writeRow(List<Object> row, BufferedWriter csvWriter) throws IOException {
// 写入文件头部
for (Object data : row) {
StringBuffer sb = new StringBuffer();
String rowStr = sb.append("\"").append(data).append("\",").toString();
csvWriter.write(rowStr);
}
csvWriter.newLine();
}
public static File createCSVFile(HttpServletRequest request){
List< Map<String,Object>> list = new ArrayList<>();
for(int i =0;i<10;i++){
Map<String,Object> mao = new HashMap<>();
mao.put("cutomerName","zhangsan"+i);
mao.put("cutomerNam1","zhangsan"+i);
mao.put("cutomerNam2","zhangsan"+i);
mao.put("cutomerNam3","zhangsan"+i);
mao.put("cutomerNam4","zhangsan"+i);
mao.put("cutomerNam5","zhangsan"+i);
mao.put("cutomerNam6","zhangsan"+i);
mao.put("cutomerNam7","zhangsan"+i);
mao.put("cutomerNam8","zhangsan"+i);
mao.put("cutomerNam9", "2017-10-17 22:33:33 12.00");
mao.put("cutomerNam10",555555556);
/* mao.put("cutomerNam11","zhangsan"+i);
mao.put("cutomerNam12","zhangsan"+i);
mao.put("cutomerNam13","zhangsan"+i);
mao.put("cutomerNam14","zhangsan"+i);
mao.put("cutomerNam15","zhangsan"+i);
mao.put("cutomerNam16","zhangsan"+i);
mao.put("cutomerNam17","zhangsan"+i);
mao.put("cutomerNam18","zhangsan"+i);
mao.put("cutomerNam19","zhangsan"+i);
mao.put("cutomerNam20","zhangsan"+i);
mao.put("cutomerNam21","zhangsan"+i);
mao.put("cutomerNam22","zhangsan"+i);
mao.put("cutomerNam23","zhangsan"+i);
mao.put("cutomerNam24","zhangsan"+i);
mao.put("cutomerNam25","zhangsan"+i);
mao.put("cutomerNam26","zhangsan"+i);
mao.put("cutomerNam27","zhangsan"+i);
mao.put("cutomerNam28","zhangsan"+i);
mao.put("cutomerNam29","zhangsan"+i);
mao.put("cutomerNam30","zhangsan"+i);
mao.put("cutomerNam31","zhangsan"+i);
mao.put("cutomerNam32","zhangsan"+i);
mao.put("cutomerNam33","zhangsan"+i);
mao.put("cutomerNam34","zhangsan"+i);
mao.put("cutomerNam35","zhangsan"+i);
mao.put("cutomerNam36","zhangsan"+i);
mao.put("cutomerNam37","zhangsan"+i);
mao.put("cutomerNam38","zhangsan"+i);
mao.put("cutomerNam39","zhangsan"+i);
mao.put("cutomerNam40","zhangsan"+i);
mao.put("cutomerNam41","zhangsan"+i);
mao.put("cutomerNam42","zhangsan"+i);
mao.put("cutomerNam43","zhangsan"+i);
mao.put("cutomerNam44","zhangsan"+i);
mao.put("cutomerNam45","zhangsan"+i);*/
list.add(mao);
} // 设置表格头
Object[] head = {"客户姓名", "证件类型", "证件号码", "银行账号", "理财账号", "客户类型", "风险等级", "归属状况", "归属机构", "客户经理", "营销比例(%)" };
List<Object> headList = Arrays.asList(head);
// 设置数据
List<List<Object>> dataList = new ArrayList<List<Object>>();
List<Object> rowList = null;
for (int i = 0; i < list.size(); i++) {
rowList = new ArrayList<Object>();
Map<String,Object> maovo = list.get(i);
rowList.add(maovo.get("cutomerName"));
rowList.add(maovo.get("cutomerNam1"));
rowList.add(maovo.get("cutomerNam2"));
rowList.add(maovo.get("cutomerNam3"));
rowList.add(maovo.get("cutomerNam4"));
rowList.add(maovo.get("cutomerNam5"));
rowList.add(maovo.get("cutomerNam6"));
rowList.add(maovo.get("cutomerNam7"));
rowList.add(maovo.get("cutomerNam8"));
rowList.add(maovo.get("cutomerNam9"));
rowList.add(maovo.get("cutomerNam10"));
dataList.add(rowList);
}
// 导出文件路径
// String downloadFilePath = request.getContextPath();
// 导出文件名称
String fileName = "客户列表_";
// 导出CSV文件
File csvFile = CSVUtils.createCSVFile(headList, dataList, fileName);
return csvFile;
}
}

关于poi导出excel方式HSSFWorkbook(xls).XSSFWorkbook(xlsx).SXSSFWorkbook.csv的总结的更多相关文章

  1. poi做Excel数据驱动,支持.xls和.xlsx格式的excel文档,比起jxl强大不少

    import java.io.FileInputStream;import java.io.InputStream;import java.util.Iterator;import java.util ...

  2. 关于poi导出excel三种方式HSSFWorkbook,SXSSFWorkbook,csv的总结

    poi导出excel最常用的是第一种方式HSSFWorkbook,不过这种方式数据量大的话会产生内存溢出问题,SXSSFWorkbook是一种大数据量导出格式,csv是另一种excel导出的一种轻快的 ...

  3. 使用Apache POI导出Excel小结--导出XLS格式文档

    使用Apache POI导出Excel小结 关于使用Apache POI导出Excel我大概会分三篇文章去写 使用Apache POI导出Excel小结--导出XLS格式文档 使用Apache POI ...

  4. POI导出excel的三种方式

    原文链接:https://www.cnblogs.com/zhaoblog/p/7661245.html poi导出excel最常用的是第一种方式HSSFWorkbook,不过这种方式数据量大的话会产 ...

  5. 用POI导出excel时,较长的数字不想被自动变为科学计数法的解决方式(转)

    做过很多次导出excel了.都碰到一个问题,内容里如果包含一个比较长的数字,比如订单号“2546541656596”,excel会自动变成科学计数法... 弄过好几次都没有解决,最近又要导出excel ...

  6. 复杂的POI导出Excel表格(多行表头、合并单元格)

    poi导出excel有两种方式: 第一种:从无到有的创建整个excel,通过HSSFWorkbook,HSSFSheet HSSFCell, 等对象一步一步的创建出工作簿,sheet,和单元格,并添加 ...

  7. POI导出excel的简单demo

    目前使用过两种导出excel的方式,一种是如题所示的使用POI的方式进行数据的导出,这种方式一般只有在处理比较多的数据或者说需要导出的excel表格中有图片之类的需要特殊处理的文件的时候使用:还有一种 ...

  8. POI导出EXCEL经典实现

    1.Apache POI简介 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程式对Microsoft Office格式档案读和写的功能. .NET的开发人员则 ...

  9. Java POI 导出EXCEL经典实现 Java导出Excel

    转自http://blog.csdn.net/evangel_z/article/details/7332535 在web开发中,有一个经典的功能,就是数据的导入导出.特别是数据的导出,在生产管理或者 ...

随机推荐

  1. elasticsearch解决控制台中文乱码问题

    找到conf目录下的jvm.options文件,找到如下的配置行: 我将之前的UTF-8 改成GBK,ok.

  2. StringDemo

    package cn.sasa.demo2; public class StringDemo { public static void main(String[] args) { //String 底 ...

  3. 初识waindows窗体程序错题整理

    解析:A:Items表示集合B:获取或设置 ComboBox 的可编辑部分中选定的文本.C:SelectedIndex是索引D:获取或设置 控件中选定项的模板 解析:本题目考不同窗体之间跳转的方法,使 ...

  4. 百度富媒体展示允许自定义站点Logo/简介等

    今早登录百度站长平台ytkah突然发现站点信息那边可以自定义百度富媒体展示的资料.何谓富媒体(Rich Media)展示,即在搜索页面上展示图片.音乐.视频,还能在当前页播放,本文主要介绍站点logo ...

  5. what's the python之基本运算符及字符串、列表、元祖、集合、字典的内置方法

    计算机可以进行的运算有很多种,运算按种类可分为算数运算.比较运算.逻辑运算.赋值运算.成员运算.身份运算.字符串和列表的算数运算只能用+和*,字典没有顺序,所以不能进行算数运算和比较运算.比较运算中= ...

  6. 腾讯游戏DBA团队的发展自白

    BA这个岗位跟仓管员很像,就是每天给别人发点货,别人在你这儿放点货,DBA工作就是把货尽快给送出去或者让人家尽快放进来.当然,还有一份重要的工作,就是让仓库里摆放的货物尽可能整齐,这也是仓管员的本职工 ...

  7. v-show 和 v-if 对 v-chart的影响

    借鉴:https://blog.csdn.net/xiaxiangyun/article/details/78909991 使用v-show控制tab切换 其中一个tab数据请求后显示第二个tab,第 ...

  8. pymysql下报错:numpy.float64 object has no attribute 'translate' 可能是pandas版本的问题

    pymysql下报错:numpy.float64 object has no attribute 'translate'.定位到db.merge函数中,dataframe中浮点型元素的类型为numpy ...

  9. golang 的 buffered channel 及 unbuffered channel

    The channel is divided into two categories: unbuffered and buffered. (1) Unbuffered channelFor unbuf ...

  10. HBase 数据迁移方案介绍 (转载)

    原文地址:https://www.cnblogs.com/ballwql/p/hbase_data_transfer.html 一.前言 HBase数据迁移是很常见的操作,目前业界主要的迁移方式主要分 ...