java使用poi导出excel例子

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lzc1993lzc/article/details/83055513
java导出某个页签:

第一步:先在jsp新建一个导出界面按钮:
<a id="export" class="mini-button" iconCls="icon-download" onclick="exportexcel();" plain="true">导出</a>	

第二步:在js中新建导出方法:

//导出数据到EXCEL表
function exportexcel(){
	var rows1 = treegrid.getRootNode();
	var rows = rows1.children;
          	var bi_id = "";
			for(var i = 0 ;i<rows.length;i++){				
				if(i==0){
					bi_id+="'";
					bi_id+=rows[i].BI_ID.toString();
				}else{
					bi_id+="','";
					bi_id+=rows[i].BI_ID.toString();
				}
			}
	bi_id+="'";
	var dp = mini.get("datePicker").value.format('yyyy-MM');
	if(tabsName=="BI"){
		var url1 = resources.webappName + "/projectTechnical/ExportExcelTechnical?bi_id=" + bi_id+"&dp="+dp;
 		window.location.href = url1;
 		
	}else if (tabsName=="IN"){
		var url1 = resources.webappName + "/projectTechnical/ExportExcelTechnical_IN?bi_id=" + bi_id+"&dp="+dp;
		window.location.href = url1; 
		
	}else{
		var url1 = resources.webappName + "/projectTechnical/ExportExcelTechnical_FF?bi_id=" + bi_id+"&dp="+dp;
		window.location.href = url1; 
		
	}		
}	


第三步:在servlet新建一个ExportExcelTechnical文件:

package gdzc2015.servlet.projectTechnical;

import gdzc2015.service.projectTechnical.projectTechnicalExpXls.TechnicalProjectExporter;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.PrintSetup;
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.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFPrintSetup;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.bl.platform.tools.json.JSONArray;
import com.bl.platform.tools.json.JSONException;
import com.bl.platform.tools.json.JSONObject;
import com.sdjxd.pms.platform.data.DbOper;

@SuppressWarnings("serial")
public class ExportExcelTechnical extends HttpServlet {
	private TechnicalProjectExporter rpexper = new TechnicalProjectExporter();
	/**
	 * Constructor of the object.
	 */
	public ExportExcelTechnical() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String bi_id = request.getParameter("bi_id");
		String dp = request.getParameter("dp");
		bi_id=bi_id.replace("'","'");
		String year = dp.substring(0,4);
		String date = dp.substring(5,7);
		String sql = "SELECT a.bi_name,a.bi_id,a.bi_code,a.bi_no,a.bi_build_type,c.BUILD_STAGE,a.BI_BUDGET_NO,a.BI_BEGIN_DATE,a.BI_PID,a.BI_LEVEL,b.BI_TOTAL_INVEST,b.BI_PLAN_INVEST,d.START_DATE,d.PAUSE_DATE FROM " ;
		sql +="(select  rownum px,bi_name,bi_id,bi_code,bi_no,bi_build_type,BI_BUDGET_NO,BI_BUDGET_APPROVAL,BI_BEGIN_DATE,BI_PID,BI_LEVEL from project_library  start with bi_id in (" + bi_id + ") connect by prior bi_id = bi_pid order siblings by bi_no) a ";
		sql +=" left join (SELECT * FROM project_report where report_date ='" +date +"' and report_year = '"+year+"' and project_id in(SELECT bi_id FROM project_library where bi_type = 7)) b on b.project_id = a.bi_id ";
		sql +=" left join (SELECT DECODE(BUILD_STAGE,0,'预留空',1,'本年新建项目',2,'本年续建项目',3,'投运项目') BUILD_STAGE,bi_id FROM project_stage_config where bi_id in (SELECT bi_id FROM project_library where bi_type = 7)and build_date = '"+year+"') c on a.bi_id = c.bi_id ";
		sql +=" left join (select substr(start_date, 1, 10) start_date,substr(pause_date, 1,10) pause_date,bi_id from (select bi_id, max(start_date) start_date,max(pause_date) pause_date from project_cycle_config group by bi_id, pause_date) ";
		sql +=" where substr(start_date, 1, 7) <= '"+dp+"' and substr(nvl(pause_date, '9999-12-31'), 1, 7) >= '"+dp+"' and bi_id in(SELECT bi_id FROM project_library where bi_type = 7)) d on a.bi_id = d.bi_id ";
		sql += " where a.bi_level in (0,1) or a.bi_id in(select pcc.bi_id from project_cycle_config pcc where substr(pcc.start_date, 1, 7) <= '"+dp+"' and substr(nvl(pcc.pause_date, '9999-12-31'),1,7) >= '"+dp+"') order by a.px";
		ResultSet rs;
		try {
			rs = DbOper.executeQuery(sql);
			List<Map<String,Object>> rows = new ArrayList<Map<String,Object>>();
			while (rs.next()) {
				Map row = new HashMap();
				for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
					row.put(rs.getMetaData().getColumnName(i).toUpperCase(),
							rs.getObject(i));
				}
				rows.add(row);
			}

			String [][] BiaoTi = {
					{"项目ID","父ID","层级","项目名称","项目唯一编码","项目排序编码","建设类型","建设阶段","概(预)算批准文号","开工日期","计划投资","","项目录入及终止时间",""},
					{"","","","","","","","","","","计划总投资","本年计划投资","开始时间","停缓时间"},
					{"BI_ID","BI_PID","BI_LEVEL","BI_NAME","BI_CODE","BI_NO","BI_BUILD_TYPE","BUILD_STAGE","BI_BUDGET_NO","BI_BEGIN_DATE","BI_TOTAL_INVEST","BI_PLAN_INVEST","START_DATE","PAUSE_DATE"}
			};
			SXSSFWorkbook workbook = rpexper.exportExcel(BiaoTi,rows,"");
			
			String title = "生产技改项目";
			String fileName = title + "-项目基本信息" +".xlsx";
			fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1"); // 取消乱码
			response.setContentType("octets/stream");
			response.addHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			OutputStream out = response.getOutputStream();
			workbook.write(out);
			out.close();
			System.out.println("导出Excel");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}
}


第四步:由于第三步引用了这个文件;TechnicalProjectExporter()来画表,所以加上这个文件:


package gdzc2015.service.projectTechnical.projectTechnicalExpXls;

import gdzc2015.common.excel.reader.Interface.IExporter;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.PrintSetup;
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.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;

public class TechnicalProjectExporter implements IExporter{
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public SXSSFWorkbook exportExcel(String[][] BiaoTi,List<Map<String,Object>> rows,String curDate){
		SXSSFWorkbook workbook = new SXSSFWorkbook(); // 创建工作薄,相当于一个文件

		Sheet sheet = workbook.createSheet(); // 创建一个表
		//sheet.setDefaultColumnWidth((short) 3); // 设置默认列宽
		//sheet.setColumnWidth(0, 18 * 256); // 设置单位列列宽

		sheet.setMargin(XSSFSheet.TopMargin, 0.64); // 页边距(上)
		sheet.setMargin(XSSFSheet.BottomMargin, 0.64); // 页边距(下)
		sheet.setMargin(XSSFSheet.LeftMargin, 0.64); // 页边距(左)
		sheet.setMargin(XSSFSheet.RightMargin, 0.64); // 页边距(右)

		PrintSetup ps = sheet.getPrintSetup();
		ps.setPaperSize(PrintSetup.A4_PAPERSIZE); // 设置纸张大小
		ps.setLandscape(true); // 打印方向,true:横向,false:纵向(默认)

		// 标题样式
		CellStyle titleStyle = workbook.createCellStyle();
		titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 水平居中
		titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中
		// 标题字体
		Font titleFont = workbook.createFont();
		titleFont.setFontHeightInPoints((short) 14); // 字体大小
		titleFont.setFontName("宋体");
		titleStyle.setFont(titleFont);

		// 填报单位的样式
		CellStyle titleStyle_2 = workbook.createCellStyle();
		titleStyle_2.setAlignment(XSSFCellStyle.ALIGN_RIGHT); // 水平居右
		titleStyle_2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中
		// 标题字体
		Font titleFont_2 = workbook.createFont();
		titleFont_2.setFontHeightInPoints((short) 11);
		titleFont_2.setFontName("宋体");
		titleStyle_2.setFont(titleFont_2);

		// 填报单位的样式
		CellStyle titleStyle_u = workbook.createCellStyle();
		titleStyle_u.setAlignment(XSSFCellStyle.ALIGN_LEFT); // 水平居左
		titleStyle_u.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中
		// 标题字体
		Font titleFont_u = workbook.createFont();
		titleFont_u.setUnderline(XSSFFont.U_SINGLE);
		titleFont_u.setFontHeightInPoints((short) 11);
		titleFont_u.setFontName("宋体");
		titleStyle_u.setFont(titleFont_u);

		// 表头样式
		CellStyle headerStyle = workbook.createCellStyle();
		headerStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 水平居中
		headerStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中
		headerStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下边框
		headerStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); // 左边框
		headerStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); // 上边框
		headerStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); // 右边框
		headerStyle.setWrapText(true); // 设置多行显示
		//这两句话是表示将表头单元格格式设置为文本型,在后面只要调用-----.setDataFormat(format.getFormat("@"))的方法就可以将数据设置为文本型。
		DataFormat format = workbook.createDataFormat();    
		headerStyle.setDataFormat(format.getFormat("@"));
		// 表头字体
		Font headerFont = workbook.createFont();
		headerFont.setFontHeightInPoints((short) 9);
		headerFont.setFontName("宋体");
		headerStyle.setFont(headerFont);

		// 数据样式
		CellStyle dataStyle = workbook.createCellStyle();
		dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 水平居中
		dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中
		dataStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下边框
		dataStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); // 左边框
		dataStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); // 上边框
		dataStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); // 右边框
		dataStyle.setDataFormat(format.getFormat("@"));      //将数据单元格格式设置为文本类型  
		// 数据字体
		Font dataFont = workbook.createFont();
		dataFont.setFontHeightInPoints((short) 9);
		dataFont.setFontName("宋体");
		dataStyle.setFont(dataFont);

		// 尾部样式
		CellStyle footStyle = workbook.createCellStyle();
		footStyle.setAlignment(XSSFCellStyle.ALIGN_LEFT); // 水平居中
		footStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中
		// 尾部字体
		Font footFont = workbook.createFont();
		footFont.setFontHeightInPoints((short) 11);
		footFont.setFontName("宋体");
		footStyle.setFont(footFont);

		CellStyle commonStyle = workbook.createCellStyle();
		commonStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下边框
		commonStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); // 左边框
		commonStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); // 上边框
		commonStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); // 右边框


		String tbdwmc = "";
		String shr = "";
		String tbr = "";
		Object obj = rows.size()==0?"":rows.get(0).get("CREATEORG");
		tbdwmc = obj==null?"":obj.toString();
		String title = "生产技改项目";
		// 表格标题行
		Row row0 = sheet.createRow(0);
		row0.setHeight((short)(3 * 256));
		Cell cell0_0 = row0.createCell(0); // 创建单元格,参数说明的是第几个单元格
		cell0_0.setCellStyle(titleStyle);
		cell0_0.setCellValue(title); // 设置单元格 和里面的内容

		Row row1 = sheet.createRow(1);
		row1.setHeight((short) (2 * 256));
		Cell cell1_0 = row1.createCell(0); // 创建单元格,参数说明的是第几个单元格
		cell1_0.setCellStyle(titleStyle_2);
		cell1_0.setCellValue("填报单位: "); // 设置单元格 和里面的内容
		Cell cell1_2 = row1.createCell(2); // 创建单元格,参数说明的是第几个单元格
		cell1_2.setCellStyle(titleStyle_u);
		cell1_2.setCellValue(tbdwmc); // 设置单元格 和里面的内容		
		
		sheet.setColumnWidth(0, 40*256);
		sheet.setColumnWidth(1, 40*256);
		sheet.setColumnWidth(2, 40*256);
		sheet.setColumnWidth(3, 40*256);
		sheet.setColumnWidth(4, 30*256);
		sheet.setColumnWidth(5, 30*256);
		Row row = null;
		Cell cell = null;
		for(int i = 2 ; i<5 ; i++){
			row = sheet.createRow(i);
			row.setHeight((short)(2 * 256));
			for(int j = 0 ;j < BiaoTi[i-2].length;j++){
				cell = row.createCell(j);
				cell.setCellValue(BiaoTi[i-2][j]);
				cell.setCellStyle(headerStyle);
				
			}
		}
		sheet.getRow(4).setZeroHeight(true);

		
		// 合并单元格
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 13)); // 合并大标题行
		sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 3));
		sheet.addMergedRegion(new CellRangeAddress(1, 1, 4, 13));
		sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 0));
		sheet.addMergedRegion(new CellRangeAddress(2, 3, 1, 1));
		sheet.addMergedRegion(new CellRangeAddress(2, 3, 2, 2));
		sheet.addMergedRegion(new CellRangeAddress(2, 3, 3, 3));
		sheet.addMergedRegion(new CellRangeAddress(2, 3, 4, 4));
		sheet.addMergedRegion(new CellRangeAddress(2, 3, 5, 5));
		sheet.addMergedRegion(new CellRangeAddress(2, 3, 6, 6));
		sheet.addMergedRegion(new CellRangeAddress(2, 3, 7, 7));
		sheet.addMergedRegion(new CellRangeAddress(2, 3, 8, 8));
		sheet.addMergedRegion(new CellRangeAddress(2, 3, 9, 9));
		sheet.addMergedRegion(new CellRangeAddress(2, 2, 10, 11));
		sheet.addMergedRegion(new CellRangeAddress(2, 2, 12, 13));

		String[] names = BiaoTi[BiaoTi.length-1];

		// 数据填充
		for (int i = 0; i < rows.size(); i++) {
			Row dataRow = sheet.createRow(5 + i);
			Map<String,Object> project = rows.get(i);
			for (int j = 0; j <names.length; j++) {
				Cell dataCell = dataRow.createCell(j);
				dataCell.setCellStyle(dataStyle);
				obj = project.get(names[j]);
				dataCell.setCellValue(obj==null?"":obj.toString());
			}
		}
		sheet.setColumnHidden(0,true);
		sheet.setColumnHidden(1,true);
		sheet.setColumnHidden(2,true);
		

//		// 表尾部
//		int weiRowNum = rows.size() + 7;
//		Row weiRow = sheet.createRow(weiRowNum);
//						
//		Cell shr_c = weiRow.createCell(2);
//		shr_c.setCellStyle(footStyle);
//		shr_c.setCellValue("" + shr);
//						
//		Cell zbr_c = weiRow.createCell(11);
//		zbr_c.setCellStyle(footStyle);
//		zbr_c.setCellValue("" + tbr);
				
		//DateFormat df = new SimpleDateFormat("yyyy-MM");
		//DateFormat df2 = new SimpleDateFormat("yyyy年MM月");
		//String dateForStr = rows.getJSONObject(0).getString("CREATEDATE");
		//Date date = df.parse(tbsj);
		//dateForStr = df2.format(date);
				
		/*XSSFCell tbsj_c = weiRow.createCell(20);
		tbsj_c.setCellStyle(footStyle);
		tbsj_c.setCellValue("填报时间:" + dateForStr);

		sheet.addMergedRegion(new CellRangeAddress(weiRowNum, weiRowNum, 2, 10)); // 合并尾部
		sheet.addMergedRegion(new CellRangeAddress(weiRowNum, weiRowNum, 11, 19)); // 合并尾部
		sheet.addMergedRegion(new CellRangeAddress(weiRowNum, weiRowNum, 20, 29)); // 合并尾部
*/
		return workbook;
	}
}

对应的jar包下载地址:poi所有需要的jar下载(3.8版本)

猜你喜欢

转载自blog.csdn.net/lzc1993lzc/article/details/83055513
今日推荐