Home > Java > javaTutorial > body text

How to export data to excel file using java

坏嘻嘻
Release: 2018-09-15 10:53:22
Original
8944 people have browsed it

The content of this article is about how to use java to export data into excel files. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

This article mainly talks about how to use java to export data to Excel files , in xls format.

For example: I want to export the data I query from the front desk into an excl format file. The query conditions (data) from the front desk need to be passed to the backend. The backend gets the data, writes SQL, and queries from the database; the data is obtained (the same as the data queried from the front desk. The data queried here is a list object. Collection), and then generate the excl file (the data is in the file, and the file name, location, and content can all be changed).

The first step: the background gets the front-end query conditions and queries the data(This step does not What to writeHow to export data to excel file using javaHow to export data to excel file using javaHow to export data to excel file using java)

1. Get the front page in the background The data. You can use json to pass the value, or you can use url to pass it. Use whichever one you want. After all, those who achieve first come first

json passing value example: (The example written may not match the data behind it, but the meaning is correct That’s it)

var data = $("#fromid").serializeObject();//表单变为json格式字符串  
//没有form表单的可以自己认为创建一个json字符串  
//var data = jQuery.parseJSON('{"FPHM":null,"FDBH":null}');  
data["FPHM"]=FPHMs;//页面的查询条件,将data传递到后台  
data["FDBH"]=_FDBH;	
$.ajax({	    
	beforeSend: function(xhr){
		xhr.setRequestHeader('Authorization', 'Bearer ' + $.session.get("token"));
		     },	    
	url: "",//你的url	   
	type: "post",	    
	contentType: 'application/json;charset=utf-8',	    
	dataType: "json",	    
	data: JSON.stringify(data),//传递格式为json格式	    
	success: function(data){			   
			$.messager.alert("提示","成功"+data,"info");	 	     
		},	    
	async: true,	    
	error: function(er) {}	
});
Copy after login

url passing, (this is simple, it is an ordinary url, which is used to assemble the parameters and corresponding data later. This article is not mainly about Talking about transfer, just a demonstration example)

##Example:

function clickdown(){//这里演示传递两个参数  
	var prnteTest=document.getElementById("prnte").value;   
	var prnteName=document.getElementById("prnteName").value;  
	location.href='url?prnteTest='+prnteTest+'&prnteName='+prnteName;  
}
Copy after login

2. Get the query data in the database (This is not too important and simple Wrote How to export data to excel file using java)How to export data to excel file using java

This is the sql statement. How can I demonstrate this? It’s just sql. What do you think? If you want to generate any data, just use SQL to check it.

I am not mainly interested in how to parse json format data, The url I use Pass the data Use the format

##

String name = request.getParameter("name");
Copy after login
to get Data,

If it is passed to the background in json format, the data will be in the form of

{ "name": 3,"post": 1 ,
 "rows": [{"JLBH":30005,"HTH":40200,"WLDW":"0316","NAME":"深圳市控股公司",
 "DTID":585,"DT_NAME":"珠宝采购","FKJE":234.0}]}
Copy after login

可以使用下面的进行解析

JSONObject jsonObj = JSONObject.fromObject(data);
Stringname =jsonObj.getParameter("name");
Copy after login

如果上面方法不能够解析json格式字符串,可自行百度。网上不少正解(毕竟本文主要讲的不是这个How to export data to excel file using javaHow to export data to excel file using java)。

得到数据之后,组装sql语句,在数据库中查询即可,这里不演示怎么查询的,结果为一个list集合里面存放着要导出的数据

第二步:生成excel文件

根据前台得到的条件,从数据库中得到数据,导出的表头

	/**
	* 测试 导出xls文件的表头	 
	*/	
	public static final String[] TestToXls = { "编号","设计人员工号", "设计人员姓名","开发人员工号", "开发人员姓名", "测试人员工号", "测试人员姓名"};
Copy after login

其中list存放的是一个对象,类似javaBean:

List<Test> listTest = new ArrayList<Test>();
Copy after login

形如:

public class Test{
	private String idd;//编号
	private String designId;//设计人员工号
	private String designName;//设计人员姓名
	private String developId;//开发人员工号
	private String developName;//开发人员姓名
	private String testId;//测试人员工号
	private String testName;//测试人员姓名
	//对应的set,get 省略
}
Copy after login

我使用的是Mybatis,其中有一个resultType,为返回类型。

形如:

<select id="findAllUser"parameterType="java.util.Map"resultType="com.test.Test" >
	select pr.qid as idd,--这里的as 后跟的,	
	pr.des_id as designId, pr.des_name as designName,	
	pr.de_id as developId, pr.de_name as developName,	
	ps.te_id as testId, ps.te_name as testName
	from ps_test_red pr left join ps_test_em ps on ps.id=pr.sys_id 
	where pr.par_nme_te > #{prnte}--组装sql语句,查询出数据
</select>
Copy after login

导出文件方法

public void toExcel() {	
	//这里为导出文件存放的路径	
	String filePath ="C:\\Users\\USER" + UUID.randomUUID() + "\\";	
	//加入一个uuid随机数是因为	
	//每次导出的时候,如果文件存在了,会将其覆盖掉,这里是保存所有的文件	
	File file = new File(filePath);	
	if (!file.exists()) {		
		file.mkdirs();	
	}
	
	SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");	
	// 给要导出的文件起名为 "测试导出数据表_时间.xls"	
	String filePath2 = filePath + "测试导出数据表" + "_" + fmt.format(new Date()) + ".xls";	
	WritableWorkbook wb = null;	
	try {		
		File file2 = new File(filePath2);		
		if (!file2.exists()) {//不存在,创建			
			file2.createNewFile();		
		}		
		wb = Workbook.createWorkbook(file2);//创建xls表格文件
	
		// 表头显示
		WritableCellFormat wcf = new WritableCellFormat();		
		wcf.setAlignment(Alignment.CENTRE);// 水平居中		
		wcf.setWrap(true);		
		wcf.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直居中		
		wcf.setFont(new WritableFont(WritableFont.TIMES,13, WritableFont.BOLD));// 表头字体 加粗 13号		
		wcf.setBackground(jxl.format.Colour.PERIWINKLE);
		// 内容显示		
		WritableCellFormat wcf2 = new WritableCellFormat();		
		wcf2.setWrap(true);//设置单元格可以换行		
		wcf2.setAlignment(Alignment.CENTRE);//水平居中		
		wcf2.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直居中		
		wcf2.setFont( new WritableFont(WritableFont.TIMES,11));// 内容字体 11号

		//导出的xls的第一页,第二页就是0换成1,“sheet1”,也可以修改为自己想要的显示的内容
		WritableSheet ws = wb.createSheet("sheet1", 0);		
		//WritableSheet ws2 = wb.createSheet("sheet2", 1);//第2个sheet页		
		ws.addCell(new Label(0,0, "导出结果"));//代表着表格中第一列的第一行显示查询结果几个字

		// 导出时生成表头		
		for (int i = 0; i < TestToXls.length; i++) {
			//i,代表的第几列,1,代表第2行,第三个参数为要显示的内容,第四个参数,为内容格式设置(按照wcf的格式显示)			
			ws.addCell(new Label(i, 1, TestToXls[i],wcf));//在sheet1中循环加入表头
		}
				
		//查询出来的数据,这个方法是演示所用		
		String sql="com.Test.Service.findAllUser";//sql为mybatis框架下的路径		
		Map<String, Object> map = new HashMap<String, Object>();//map里为存放前台的条件
		map.put("prnte",  this.getParameter("prnteTest"));
		List<Test> listTest = TestService.findAllList(sql, map);
		int k =2 ;//从第三行开始写入数据
		
		for (int i = 0; i < listTest.size(); i++) {			
			ws.addCell(new Label(0, k, listTest.get(i).getIdd(), wcf2));
			ws.addCell(new Label(1, k, listTest.get(i).getDesignId(),wcf2));
			ws.addCell(new Label(2, k, listTest.get(i).getDesignName(),wcf2));
			ws.addCell(new Label(3, k, listTest.get(i).getDevelopId(),wcf2));
			ws.addCell(new Label(4, k, listTest.get(i).getDevelopName(),wcf2));
			ws.addCell(new Label(5, k, listTest.get(i).getTestId(),wcf2));
			ws.addCell(new Label(6, k, listTest.get(i).getTestName(),wcf2));
			//ws.mergeCells(4, 5, 5, 5);//合并两列,按参数顺序,意思是第4列的第五行,跟第五列的第五行合并为一个单元格			
			k++;		
		}		
		wb.write();//写入,到这里已经生成完成,可以在相应目录下找到刚才生成的文件	
	} catch (IOException e) {
		e.printStackTrace();	
	} catch (JxlWriteException e) {
		e.printStackTrace();	
	} catch (WriteException e) {
		e.printStackTrace();	
	} finally {		
		try {			
			if (wb != null) {
				wb.close();
			}		
		} catch (WriteException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}	
	//这个是我们项目中,是把刚才生成的文件,响应到前台,进行下载、保存,可省略。	
	downLoadFile(filePath2);
}
Copy after login

响应到前台(就是读取文件,网上很多)

public void downLoadFile(String filePath) {
			
	FileInputStream in = null;		
	ServletOutputStream out = null;		
	BufferedOutputStream toOut = null;		
	try {			
		in = new FileInputStream(new File(filePath));			
		byte[] buffer = new byte[in.available()];			
		while (in.read(buffer) != -1) {				
			HttpServletResponse response = this.getContext().getResponse();//从application中得到response				
			response.reset();// 清空				
			// 设置响应的文件的头文件格式
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition",
					"attachment;filename="+ new 
					String(fileName.getBytes("GBK"),"ISO8859-1"));
			response.addHeader("Content-type", "application-download");
			// 获取响应的对象流
			out = response.getOutputStream();
			toOut = new BufferedOutputStream(out);
			toOut.write(buffer);
			toOut.flush();
		}		
	} catch (Exception e) {	
		e.printStackTrace();		} 
	finally {
		try {
			if(in!=null) {	
				in.close();	
			}				
			if(out != null) {
				out.close();
			}
			if(toOut != null) {
				toOut.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
}
Copy after login

导出文件大致为:

How to export data to excel file using java

The above is the detailed content of How to export data to excel file using java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!