Java导出Excel表格、Txt到浏览器下载
文章目录
Java导出Excel表格、Txt到浏览器下载
一. pom依赖
二. 工具类
三、后台
四、前端
注:若只需要导出Txt则不需要Excel的pom包和工具类
一. pom依赖
org.apache.poi
poi
3.17
org.apache.poi
poi-ooxml
3.17
org.apache.poi
poi-ooxml-schemas
3.17
二. 工具类
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 list=new ArrayList<>();
Collections.addAll(list, ids.split(","));
VO mv=new VO();
mv.setIds(list);
List medicines=medicineService.selectAll(mv);
StringBuilder sb = new StringBuilder("编号,图片地址,进价,售价,药品名称\r\n");
if(medicines!=null&&medicines.size()>0){
for(int i=0;i
导出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 list=new ArrayList<>();
//分割ids字符串得到数组并放入集合
Collections.addAll(list, ids.split(","));
mv.setIds(list);
//查询所有信息放到集合中
List medicines=medicineService.selectAll(mv);
//设置导出信息
Workbook wk=ExcelUtils.exportExcel(titles,"药品信息");
XSSFSheet sheet=(XSSFSheet) wk.getSheet("药品信息");
//取出集合中的数据放到表格中
for(int i=0;i
四、前端
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(
" "+
" "+
""+medicine.m_number+" "+
""+medicine.m_name+" "+
""+medicine.m_type+" "+
""+medicine.m_description+" "+
""+medicine.m_state+" "+
""+medicine.m_residue+" "+
""+
"详情>>> "+
" "
);
})
},"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
Html