BufferedWriter匯出資料excel檔案
阿新 • • 發佈:2019-02-11
BufferedWriter匯出資料
BufferedWriter 將文字寫入字元輸出流,緩衝各個字元,從而提供單個字元、陣列和字串的高效寫入。 可以指定緩衝區的大小,或者接受預設的大小。在大多數情況下,預設值就足夠大了
js 頁面
//匯出資料
function exportData(){
var data = {};
if($("#memberName").val()) data.memberName = $("#memberName").val();
if($("#merberTel" ).val()) data.merbertel = $("#merberTel").val();
//建立標籤元素
var form = document.createElement('form')
form.style.display = 'none'
document.body.appendChild(form)
form.method = 'POST'
form.action = "${webroot}/admin/exportDB.do" ; //url
form.enctype = 'application/x-www-form-urlencoded'
var dataEl = document.createElement('input');
dataEl.type = 'hidden';
dataEl.name = 'data';
dataEl.value = JSON.stringify(data); //轉JSON
form.appendChild(dataEl)
form.submit()
form.target = '_blank'
}
以上無非就是建立下面的一個標籤(看懂的可以略過),作這一步的目的是可以只匯出自己查詢出來的列表:
<form method="post" action="" enctype="application/x-www-form-urlencoded" style="display:none;" target="_blank">
<input type="hidden" name="data" value="">
匯出其實和頁面查詢 有類似,input標籤中的value存放資料data
需要了解form表單中target屬性和enctype屬性,前往另一篇部落格
後臺程式碼
1.第一類
導包
import java.io.BufferedWriter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.io.output.FileWriterWithEncoding;
宣告變數
//匯出地址
private String rootPath="E:/excelFiles/";
//產生的檔名
private String tempName="member";
匯出方法(查詢匯出表所有的資料)
/**
* 匯出資料
* @param request
* @param response
* @return
*/
@SuppressWarnings("unchecked")
@RequestMapping("/exportDB")
@ResponseBody
public void exportMember(HttpServletRequest request, HttpServletResponse response){
RequestModel requestModel=BaseUtil.getModel(request, response);
Map<String,Object> map=memberServiceImpl.exportData(requestModel.getData(),null);
List<MemberEntity> list = new ArrayList<MemberEntity>();
if (map.get("data") != null) {
list = (List<MemberEntity>) map.get("data"); //map 轉list
}
try {
downLoad(list, "member", response); //方法如下
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
這裡的map,也就是從資料庫中獲取的所有資料,我後面轉成了list。每個專案的框架不同,程式碼編寫上也會也所不同。轉回話題,在這一步中是獲取你需要匯出的資料表格,是匯出所有資料,這裡不用分頁。
接下來是程式碼的重點
private void downLoad(List<MemberEntity> list, String fileName, HttpServletResponse response) throws IOException {
long time = new Date().getTime();
File file = new File(rootPath+ time + ".csv");
BufferedWriter bw = new BufferedWriter(new FileWriterWithEncoding(file, "gb2312"));
bw.write("暱稱,姓名,手機號碼,性別,年齡,郵箱");
bw.write("\n");
for (MemberEntity member : list) {
bw.write((StringUtils.isBlank(member.getNickName()) ? "-" : member.getNickName()) + ",");
bw.write((StringUtils.isBlank(member.getMemberName()) ? "-" : member.getMemberName()) + ",");
bw.write((StringUtils.isBlank(member.getMerberTel()) ? "-" : member.getMerberTel()) + ",");
if(member.getSex()==1){ //男
bw.write((StringUtils.isBlank(member.getSex.toString()) ? "-" : "男") + ",");
}else{
bw.write((StringUtils.isBlank(member.getSex().toString()) ? "-" : "女") + ",");
}
if(member.getSex()==0){ //女
bw.write((StringUtils.isBlank(member.getSex().toString()) ? "-" : "女") + ",");
}else{
bw.write((StringUtils.isBlank(member.getSex().toString()) ? "-" : "男") + ",");
}
bw.write((StringUtils.isBlank(member.getAge().toString()) ? "-" : member.getAge().toString()) + ",");
bw.write((StringUtils.isBlank(member.getMail().toString()) ? "-" : member.getMail().toString()) + ",");
bw.write("\n");
}
bw.close();
ExcelUtil.downloadCsv(file, response, fileName);
}
ExcelUtil類中方法
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
public static void downloadCsv(File file, HttpServletResponse response,String filename) {
try {
// path是指欲下載的檔案的路徑。
// File file = new File(path);
// 取得檔名。
// String filename = file.getName();
// 以流的形式下載檔案。
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 設定response的Header
response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename, "UTF-8") + ".csv"); //.csv 或則 .xls
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
toClient.write(buffer);
toClient.flush();
toClient.close();
// file.delete();
} catch (IOException ex) {
ex.printStackTrace();
}
}
2.第二類
後臺還可以這樣簡便的寫
public String downData(HttpServletRequest request,HttpServletResponse response) throws IOException {
try {
RequestModel requestModel = BaseUtil.getModel(request, response); //自己的一個工具類方法
List<Map<String, Object>> listMap = memberServiceImpl.queryMember(requestModel.getData(),null);//獲得所有資料,不分頁
long time = new Date().getTime();
File file = new File(tempFile + "/" + time + ".xls"); //tempFile 檔案產生路徑
if (!file.exists()) {
file.createNewFile();
}
List<String> titleList = new ArrayList<>();
titleList.add("nickName_" + "暱稱"); //nickName :實體類屬性
titleList.add("memberName_" + "姓名");
titleList.add("merberTel_電話號碼");
titleList.add("age_年齡");
titleList.add("sex_性別");
titleList.add("merberBirth_出生日期");
titleList.add("memberEmail_郵箱");
OutputStream out = new FileOutputStream(file);
ExcelUtil.exportExcel2(listMap, out, titleList);
ExcelUtil.download(file, response);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
附上service層
// 返回型別 List<Map<String, Object>>
public List<Map<String, Object>> queryMember(Map<String, Object> params, Page page) {
StringBuffer sqlBuf = new StringBuffer("SQL語句寫在下面");
if (params == null) {
params = new HashMap<String, Object>();
}
if (params.containsKey("memberTel")) {
sqlBuf.append(" and ts.member_tel=:memberTel");
}
if (params.containsKey("memberName")) {
sqlBuf.append(" and tm.member_name like CONCAT('%',:memberName,'%')");
}
return this.customerJPARepository.queryListEntity(sqlBuf.toString(), params); //這個是Dao層自定義查詢方法,我定義的是JPA框架中的方法
}
以上sex和birthday直接在寫SQL時進行性別判斷
//SQL中後面的別名 對應實體類中的屬性
SELECT IFNULL(tm.nick_name,'--') nickName,IFNULL(tm.member_name,'--') memberName,IFNULL(tm.merber_tel,'--') merberTel,IFNULL(tm.age,'--') age,
CASE tm.sex WHEN 1 THEN '男' WHEN 0 THEN '女' ELSE '--' END sex,
IFNULL(DATE_FORMAT(tm.birthday,'%Y-%m-%d %T'),'--') merberBirth,IFNULL(tm.member_email,'--') memberEmail
FROM t_member tm
ExcelUtil工具類
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.hssf.util.HSSFColor;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class ExcelUtil{
/**
* List<Map<String, Object>> list
* @param list
* @param out
*/
public static void exportExcel1(List<Map<String, Object>> list,OutputStream out) {
// 宣告一個工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一個表格
HSSFSheet sheet = workbook.createSheet("sheet1");
// 設定表格預設列寬度為15個位元組
sheet.setDefaultColumnWidth((short) 15);
// 生成一個樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設定這些樣式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一個字型
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字型應用到當前的樣式
style.setFont(font);
// 生成並設定另一個樣式
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一個字型
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字型應用到當前的樣式
style2.setFont(font2);
// 宣告一個畫圖的頂級管理器
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 定義註釋的大小和位置,詳見文件
HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,0, 0, 0, (short) 4, 2, (short) 6, 5));
// 設定註釋內容
comment.setString(new HSSFRichTextString("可以在POI中添加註釋!"));
// 設定註釋作者,當滑鼠移動到單元格上是可以在狀態列中看到該內容.
comment.setAuthor("excels");
// 產生表格標題行
if (list != null && list.size() > 0) {
HSSFRow row = sheet.createRow(0);
// 生成頭
Set<String> set = list.get(0).keySet();
String[] tempArr = new String[set.size()];
String[] colArr = new String[set.size()];
set.toArray(tempArr);
for (int i = 0; i < tempArr.length; i++) {
String[] temp = tempArr[i].split("_");
colArr[Integer.parseInt(temp[0])] = tempArr[i];
}
for (int i = 0; i < colArr.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
String[] temp = colArr[i].split("_");
cell.setCellValue(temp[1]);
}
int index = 1;
for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = list.get(i);
row = sheet.createRow(index);
index++;
for (int j = 0; j < colArr.length; j++) {
HSSFCell cell = row.createCell(j);
cell.setCellStyle(style2);
if (j == colArr.length - 1) {
try {
String content = String.valueOf(map.get(colArr[j]));
JSONObject jsonObject = JSON.parseObject(content); //需要一個 fastjson.jar包
if (jsonObject.containsKey("type")) {
switch (String.valueOf(jsonObject.get("type"))) {
case "text":
cell.setCellValue(String.valueOf(jsonObject.get("content")));
break;
case "image":
cell.setCellValue("[圖片]");
break;
case "car":
cell.setCellValue(String.valueOf(jsonObject.getJSONObject("content").get("carModelName")));
break;
default:
cell.setCellValue("");
break;
}
}
} catch (Exception ex) {
ex.printStackTrace();
cell.setCellValue("");
}
} else {
cell.setCellValue(String.valueOf(map.get(colArr[j])));
}
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* List<Map<String, Object>> list
*
* @param list
* @param out
* @param titleList
*/
public static void exportExcel2(List<Map<String, Object>> list,OutputStream out, List<String> titleList) {
// 宣告一個工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// '生成一個表格'
HSSFSheet sheet = workbook.createSheet("sheet1");
// 設定表格預設列寬度為15個位元組
sheet.setDefaultColumnWidth((short) 15);
// 生成一個樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設定這些樣式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一個字型
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字型應用到當前的樣式
style.setFont(font);
// 生成並設定另一個樣式
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一個字型
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字型應用到當前的樣式
style2.setFont(font2);
// 宣告一個畫圖的頂級管理器
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 定義註釋的大小和位置,詳見文件
HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,0, 0, 0, (short) 4, 2, (short) 6, 5));
// 設定註釋內容
comment.setString(new HSSFRichTextString("可以在POI中添加註釋!"));
// 設定註釋作者,當滑鼠移動到單元格上是可以在狀態列中看到該內容.
comment.setAuthor("excels");
// 產生表格標題行
if (titleList != null && titleList.size() > 0) {
String[] colArr = new String[titleList.size()];
HSSFRow row = sheet.createRow(0);
// 生成頭
for (int i = 0; i < titleList.size(); i++) {
String title = titleList.get(i);
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
String[] temp = title.split("_");
colArr[i] = temp[0];
cell.setCellValue(temp[1]);
}
int index = 1;
for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = list.get(i);
row = sheet.createRow(index);
index++;
for (int j = 0; j < colArr.length; j++) {
HSSFCell cell = row.createCell(j);
cell.setCellStyle(style2);
cell.setCellValue(String.valueOf(map.get(colArr[j])));
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
//下載
public static void download(File file, HttpServletResponse response) {
try {
// path是指欲下載的檔案的路徑。
// File file = new File(path);
// 取得檔名。
String filename = file.getName();
// 以流的形式下載檔案。
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 設定response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
toClient.write(buffer);
toClient.flush();
toClient.close();
file.delete();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
maven 中需要加入jar包
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
其實 對資料的匯出,有很多種寫法,這是我所用到的一類!