Java導出Excel表格、Txt到瀏覽器下載
- 注:若只需要導出Txt則不需要Excel的pom包和工具類
一. pom依賴
<!-- ****************************************** poi導出excel ************************************ -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
二. 工具類
- ExcelUtil 用於生成工作簿對象和sheet對象等
public class ExcelUtils {
/**
*
* @param titles 表格標題
* @param name sheet名
* @return
* @throws Exception
*/
public static Workbook exportExcel(String[] titles,String name) throws Exception{
// 新建工作簿對象
XSSFWorkbook workBook = new XSSFWorkbook();
// 創建sheet對象
XSSFSheet sheet = workBook.createSheet(name);
// 創建行,標題行
XSSFRow row = sheet.createRow(0);
for(int i = 0; i < titles.length; i++){
// 創建單元格
XSSFCell cell = row.createCell(i);
// 設置單元格內容
cell.setCellValue(titles[i]);
}
return workBook;
}
}
- BuildPath 用於創建響應對象輸出流
public class BuildPath {
/**
*
* @param response 響應對象
* @param fileName 輸出內容
* @return 響應對象輸出流
* @throws IOException
*/
public static OutputStream Manual_Saving(HttpServletResponse response,String fileName) throws IOException{
//瀏覽器自選輸出路徑
response.setHeader("Content-disposition", "attachment;filename="+fileName);
response.setContentType("application/msexcel");
OutputStream out=response.getOutputStream();
return out;
}
}
三、後臺
- 導出Txt(只需要傳入需要導出表的id集合如“1,2,3”即可)
@RequestMapping("/exportTxt.do")
public void exportTerminalKey(HttpServletRequest request, HttpServletResponse response,String ids) throws Exception {
Result result=new Result(6001, false, "導出失敗");
List<String> list=new ArrayList<>();
Collections.addAll(list, ids.split(","));
VO mv=new VO();
mv.setIds(list);
List<Medicine> medicines=medicineService.selectAll(mv);
StringBuilder sb = new StringBuilder("編號,圖片地址,進價,售價,藥品名稱\r\n");
if(medicines!=null&&medicines.size()>0){
for(int i=0;i<medicines.size();i++){
sb.append(
medicines.get(i).getM_number()+","+
medicines.get(i).getM_image_addr()+","+
medicines.get(i).getM_purchase()+","+
medicines.get(i).getM_selling()+","+
medicines.get(i).getM_name()+"\r\n");
}
}
BufferedOutputStream output = null;
BufferedInputStream input = null;
//設置輸出流對象
OutputStream os =BuildPath.Manual_Saving(response, "Mediine.txt");
try{
byte[] byt = sb.toString().getBytes();
os.write(byt);
}catch(Exception e){
System.out.println("chucuo");
}finally{
os.flush();
os.close();
if(input!=null){
input.close();
}
if(output!=null){
output.close();
}
}
if(medicines!=null){
//所有信息裝入result對象
result.setCode(6000);
result.setFlag(true);
result.setMessage("導出成功");
}
}
- 導出Excel(只需要傳入需要導出表的id集合如“1,2,3”即可)
@RequestMapping("/exportMedicine.do")
public void exportDoctor(String ids,HttpServletResponse response) throws Exception{
String[] titles={"編號","圖片地址","進價","售價","藥品名稱"};
Result result=new Result(6001, false, "導出失敗");
VO mv=new VO();
List<String> list=new ArrayList<>();
//分割ids字符串得到數組並放入集合
Collections.addAll(list, ids.split(","));
mv.setIds(list);
//查詢所有信息放到集合中
List<Medicine> medicines=medicineService.selectAll(mv);
//設置導出信息
Workbook wk=ExcelUtils.exportExcel(titles,"藥品信息");
XSSFSheet sheet=(XSSFSheet) wk.getSheet("藥品信息");
//取出集合中的數據放到表格中
for(int i=0;i<medicines.size();i++){
XSSFRow row = sheet.createRow(i+1);
row.createCell(0).setCellValue(medicines.get(i).getM_number());
row.createCell(1).setCellValue(medicines.get(i).getM_image_addr());
row.createCell(2).setCellValue(medicines.get(i).getM_purchase());
row.createCell(3).setCellValue(medicines.get(i).getM_selling());
row.createCell(4).setCellValue(medicines.get(i).getM_name());
}
//設置輸出流
OutputStream out=BuildPath.Manual_Saving(response, "Medicine.xls");
wk.write(out);
wk.close();
if(medicines!=null){
//所有信息裝入result對象
result.setCode(6000);
result.setFlag(true);
result.setMessage("導出成功");
}
System.out.println(result);
}
四、前端
- JavaScript
$.post("../selectMedicineByCondition.do",{pageNum:pageNum,m_name:m_name,m_type:m_type},function(result){
//填充數據到tbody
$("#tbody").empty();//清除之前的內容
$(result.object.list).each(function(index,medicine){
$("#tbody").append(
" <tr>"+
"<td style='vertical-align:middle;'><input type='checkbox' name='check' value='"+medicine.m_id+"'></td>"+
"<td style='vertical-align:middle;'>"+medicine.m_number+"</td>"+
"<td style='vertical-align:middle;''>"+medicine.m_name+"</td>"+
"<td style='vertical-align:middle;''>"+medicine.m_type+"</td>"+
"<td style='vertical-align:middle;''>"+medicine.m_description+"</td>"+
"<td style='vertical-align:middle;''>"+medicine.m_state+"</td>"+
"<td style='vertical-align:middle;''>"+medicine.m_residue+"</td>"+
"<td style='vertical-align:middle;'>"+
"<a id='btn6' m_id="+medicine.m_id+">詳情>>></a> "+
"</tr>"
);
})
},"json");
$("input[type=checkbox]").live("change",function(){
delAll();
})
//查看所有被選中的checkbox框並記錄其id
function delAll(){
var alls=document.getElementsByName("check");
var ids=new Array();
for(var i=0;i<alls.length;i++){
if(alls[i].checked){
ids.push(alls[i].value);
}
}
$(".ids").val(ids);
}
- Html
<table class="table table-bordered table-hover definewidth m10" >
<thead>
<tr>
<th><input type="checkbox" id="checkall" onChange="checkall();"></th>
<th>藥品編號</th>
<th>藥品名稱</th>
<th>藥品類型</th>
<th>簡單描述</th>
<th>狀態</th>
<th>剩餘量</th>
<th>操作</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<form action="../exportMedicine.do" method="post" style="display: inline-block;">
<input type="hidden" class="ids" name="ids" value="">
<input type="submit" class="btn btn-success" value="導出Excel">
</form>
<form action="../exportTxt.do" method="post" style="display: inline-block;">
<input type="hidden" class="ids" name="ids" value="">
<input type="submit" class="btn btn-success" value="導出txt">
</form>