java jsp 导出execl报表

1.这是我个人实现的实例:

struts.xml配置;

<!-- 导出excel表 -->
		<action name="excel" class="com.gdcct.hospital.web.action.manage.statisticalmanage.HpExpertAboutManageAction">
			<result name="excel" type="stream">
				<param name="contentType">
					application/vnd.ms-excel
				</param>
				<param name="inputName">excelStream</param>
				<param name="contentDisposition">
					filename="expertReport.xls"
				</param>
				<param name="bufferSize">1024</param>
			</result>
		</action>


struts2 的action写法

//得到报表list;
	public List getExpertList(){
		RequestEvent req = new RequestEvent("HpStatisticalManageBLH",
				EventType.CHANNEL_TYPE_COREWEB, this.getSessionId());
		req.setFuncType(EventType.FUNC_TYPE_NEEDCHECK);
		req.setDealMethod("getExpertCount");
		req.setReqParam("loginTime", loginTime);
		req.setReqParam("logoutTime", logoutTime);
		req.setReqParam("expertCode", expertCode);
		
		ResponseEvent res = BizDelegate.getInstance().delegate(req);
		if (res == null || res.getRepCode() == null
				|| !res.getRepCode().trim().equals("0")) {
			//return this.addErrorMsg(res);
		}
		deptList=(List<HpDepartmentVO>) res.getRetResult("list");
		return deptList;
	}
	
	 public String execute(){  
	       
	        excelStream = getExcelInputStream();  
	        return "excel";  
	    }  
	
	public InputStream getExcelInputStream() {  
        //将OutputStream转化为InputStream  
        ByteArrayOutputStream out = new ByteArrayOutputStream();  
        putDataOnOutputStream(out);  
        return new ByteArrayInputStream(out.toByteArray());  
    }  
  
    public void putDataOnOutputStream(OutputStream os) {  
        jxl.write.Label label;  
        WritableWorkbook workbook;  
        try {  
            workbook = Workbook.createWorkbook(os);  
            WritableSheet sheet = workbook.createSheet("Sheet1", 0);  
            //totalx2Format.setAlignment(Alignment.CENTRE); 
           // sheet.addCell(new jxl.write.Label(0, 0, "struts2导出excel"));  
         // 定义格式, 字体, 下划线, 斜体, 粗体, 颜色
            WritableFont wf = new WritableFont(WritableFont.ARIAL, 10,
				                WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
				               jxl.format.Colour.BLACK); 
         // 创建格式化对象实例   
            WritableCellFormat totalx2Format = new WritableCellFormat(wf);   
            // 垂直居中   
            totalx2Format.setVerticalAlignment(VerticalAlignment.CENTRE);   
            // 水平居中   
            totalx2Format.setAlignment(Alignment.CENTRE);
            // 设置标题.ws.addCell(new jxl.write.Label(列(从0开始), 行(从1开始), 内容.));
            sheet.addCell(new Label(0, 0, "专家帐号",totalx2Format));
            sheet.addCell(new Label(1, 0, "专家姓名",totalx2Format)); 
            sheet.addCell(new Label(2, 0, "在线时长(小时)",totalx2Format)); 
            sheet.addCell(new Label(3, 0, "回答问题次数",totalx2Format)); 
            sheet.addCell(new Label(4, 0, "在线咨询次数",totalx2Format)); 
            sheet.addCell(new Label(5, 0, "视频次数",totalx2Format)); 
            sheet.addCell(new Label(6, 0, "登陆次数",totalx2Format)); 
            
           List<HpExpertaboutVO> arrList = getExpertList();
             if (null!=workbook&&arrList.size()>0&&arrList!=null) {
				for (int i = 0; i < arrList.size(); i++) {
					/*arrList.get(i).getExpertCode();
					arrList.get(i).getExpertName();
					arrList.get(i).getTimeLength();
					arrList.get(i).getAnswerTimes();
					arrList.get(i).getOnlineTimes();
					arrList.get(i).getVideoTimes();
					arrList.get(i).getLoginTimes();*/
				sheet.addCell(new jxl.write.Label(0, i+1, arrList.get(i).getExpertCode()));
				sheet.addCell(new jxl.write.Label(1, i+1, arrList.get(i).getExpertName()));
				
				sheet.addCell(new jxl.write.Label(2, i+1, arrList.get(i).getTimeLength()));
				
				sheet.addCell(new jxl.write.Label(3, i+1, arrList.get(i).getAnswerTimes()));
				sheet.addCell(new jxl.write.Label(4, i+1, arrList.get(i).getOnlineTimes()));
				sheet.addCell(new jxl.write.Label(5, i+1, arrList.get(i).getVideoTimes()));
				sheet.addCell(new jxl.write.Label(6, i+1, arrList.get(i).getLoginTimes()));
				}
			}
            workbook.write();  
            workbook.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }   


3.网上找的实例

import jxl.write.WritableWorkbook;

public class Jxl {

	/**
	 * 
	 * @author smart *
	 */
	public static void main(String[] args) {
		// 准备设置excel工作表的标题
		String[] title = { "编号", "产品名称", "产品价格", "产品数量", "生产日期", "产地", "是否出口3" };
		try {
			// 获得开始时间
			long start = System.currentTimeMillis();
			// 输出的excel的路径
			String filePath = "d:\\test.xls";
			System.out.println("输出的excel的路径:d:\\test.xls");
			// 创建Excel工作薄
			WritableWorkbook wwb;
			// 新建立一个jxl文件,即在C盘下生成test.xls
			OutputStream os = new FileOutputStream(filePath);
			wwb = Workbook.createWorkbook(os);
			// 添加第一个工作表并设置第一个Sheet的名字
			WritableSheet sheet = wwb.createSheet("产品清单", 0);
			Label label;
			for (int i = 0; i < title.length; i++) {
				// Label(x,y,z)其中x代表单元格的第x+1列,第y+1行, 单元格的内容是y
				// 在Label对象的子对象中指明单元格的位置和内容
				label = new Label(i, 0, title[i]);
				// 将定义好的单元格添加到工作表中
				sheet.addCell(label);
			}
			// 下面是填充数据
			/*
			 * 保存数字到单元格,需要使用jxl.write.Number 必须使用其完整路径,否则会出现错误
			 */
			// 填充产品编号
			jxl.write.Number number = new jxl.write.Number(0, 1, 20071001);
			sheet.addCell(number);
			// 填充产品名称
			label = new Label(1, 1, "金鸽瓜子");
			sheet.addCell(label);
			/*
			 * 定义对于显示金额的公共格式 jxl会自动实现四舍五入 例如 2.456会被格式化为2.46,2.454会被格式化为2.45
			 */
			jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
			jxl.write.WritableCellFormat wcf = new jxl.write.WritableCellFormat(
					nf);
			// 填充产品价格
			jxl.write.Number nb = new jxl.write.Number(2, 1, 2.45, wcf);
			sheet.addCell(nb);
			// 填充产品数量
			jxl.write.Number numb = new jxl.write.Number(3, 1, 200);
			sheet.addCell(numb);
			/*
			 * 定义显示日期的公共格式 如:yyyy-MM-dd hh:mm
			 */
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String newdate = sdf.format(new Date());
			// 填充出产日期
			label = new Label(4, 1, newdate);
			sheet.addCell(label);
			// 填充产地
			label = new Label(5, 1, "陕西西安");
			sheet.addCell(label);
			/*
			 * 显示布尔值
			 */
			jxl.write.Boolean bool = new jxl.write.Boolean(6, 1, true);
			sheet.addCell(bool);
			/*
			 * 合并单元格 通过writablesheet.mergeCells(int x,int y,int m,int n);来实现的
			 * 表示将从第x+1列,y+1行到m+1列,n+1行合并
			 * 
			 */
			sheet.mergeCells(0, 3, 2, 3);
			label = new Label(0, 3, "合并了三个单元格");
			sheet.addCell(label);
			/*
			 * 
			 * 定义公共字体格式 通过获取一个字体的样式来作为模板 首先通过web.getSheet(0)获得第一个sheet
			 * 然后取得第一个sheet的第二列,第一行也就是"产品名称"的字体
			 */
			CellFormat cf = wwb.getSheet(0).getCell(1, 0).getCellFormat();
			WritableCellFormat wc = new WritableCellFormat();
			// 设置居中
			wc.setAlignment(Alignment.CENTRE);
			// 设置边框线
			wc.setBorder(Border.ALL, BorderLineStyle.THIN);
			// 设置单元格的背景颜色
			wc.setBackground(jxl.format.Colour.RED);
			label = new Label(1, 5, "字体", wc);
			sheet.addCell(label);

			// 设置字体
			jxl.write.WritableFont wfont = new jxl.write.WritableFont(
					WritableFont.createFont("隶书"), 20);
			WritableCellFormat font = new WritableCellFormat(wfont);
			label = new Label(2, 6, "隶书", font);
			sheet.addCell(label);

			// 写入数据
			wwb.write();
			// 关闭文件
			wwb.close();
			long end = System.currentTimeMillis();
			System.out.println("----完成该操作共用的时间是:" + (end - start) / 1000);
		} catch (Exception e) {
			System.out.println("---出现异常---");
			e.printStackTrace();
		}
	}
}




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
您可以使用 JSPJavaServer Pages)导出数据到 Excel 文件。下面是一个简单的示例: 1. 首先,确保您的 JSP 页面已经包含了 Apache POI(一个用于处理 Microsoft Office 文件的 Java 库)的依赖项。您可以将以下 Maven 依赖项添加到您的项目中: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 在您的 JSP 页面中,创建一个方法来导出 Excel 文件。以下是一个示例方法: ```java <%@ page import="org.apache.poi.xssf.usermodel.XSSFWorkbook" %> <%@ page import="java.io.FileOutputStream" %> <%@ page import="java.io.IOException" %> <% // 创建一个新的工作簿 XSSFWorkbook workbook = new XSSFWorkbook(); // 创建一个工作表 XSSFSheet sheet = workbook.createSheet("Sheet1"); // 在工作表中创建行和单元格,并设置数据 for (int row = 0; row < 10; row++) { XSSFRow currentRow = sheet.createRow(row); for (int col = 0; col < 5; col++) { XSSFCell currentCell = currentRow.createCell(col); currentCell.setCellValue("Data " + (row + 1) + "-" + (col + 1)); } } // 将工作簿写入输出流 try (FileOutputStream outputStream = new FileOutputStream("path/to/output/file.xlsx")) { workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); } %> ``` 请注意,上述代码将在服务器端生成 Excel 文件,并将其保存到指定的路径下。 3. 在您的 JSP 页面中,创建一个链接或按钮,以便用户可以点击来触发导出操作: ```html <a href="export.jsp">导出 Excel</a> ``` 当用户点击该链接时,将执行导出方法,并生成 Excel 文件。 请注意,上述示例仅用于演示目的。您可能需要根据您的实际需求进行更多的定制和错误处理。另外,请确保在生产环境中采取适当的安全措施以防止潜在的安全风险。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值