利用jxl实现excel导出

【说明】

1.点击导出,取前台现有的数据通过ajax传到后台,

2.通过jxl生成服务器上的xls文件

3.ajax成功之后转到download,也就是打开保存界面:


【配置】

1.使用了struts2的注解配置


【代码】

jsp:

		//导出
	    $('#exportBtn').click(function(){
			var str = '';
	    	$('div.datagrid-view2 table.datagrid-btable')
				.find('td')
				.each(function(){
					str += $(this).text() + '%%%%';
				});
	    	
	    	$.ajax({
				url : 'scoreAction!exportExcel.action',
				type : 'POST',
				data : {
					str : str,
					fileName : 'score.xls'
				},
				dataType : 'json'
	    	}).done(function(data){
	    		if(data && data == 'success'){
			    	window.location.href = "scoreAction!downloadFile.action?fileName=score.xls";
	    		}else{
	    			$.messager.show({
						title : '失败',
						msg : '导出失败!'
					});
	    		}
	    	}).fail(function(){
	    		$.messager.show({
					title : '失败',
					msg : '导出失败!'
				});
	    	});
	    });

action:

action中添加字段fileName和它的setter,getter

添加一个方法getInputStream(),

添加注解,部分代码如下:

@Action(
		value = "scoreAction", 
		results = { 
			@Result(name = "download", type="stream",params={
		            "contentType","application/octet-stream",
		            "inputName","inputStream",
		            "contentDisposition","attachment;filename=${fileName}",
		            "bufferSize","4096"            
		    })
		})
public class ScoreAction extends BaseAction implements ModelDriven<ClazzRlLearnerPage> {
	@Autowired
	private ScoreServiceI scoreService;
	private String fileName;
	private String str;
	
	//method--public
	public void exportExcel(){
		writeJson(scoreService.exportExcel(str));
	}
	public String downloadFile(){
		return "download";
	}
	public InputStream getInputStream()
	{
		InputStream is = null;
		String filePath = 
				((ServletContext)ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT)).getRealPath("/") + "jsp\\score\\xls\\score.xls";
		
		try {
			is = new FileInputStream(new File(filePath));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		return is;
	}
	
	//getters and setters
	public String getStr() {
		return str;
	}
	public void setStr(String str) {
		this.str = str;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}

jxl实现导出excel:

//导出Excel
	public String exportExcel(String str){
		WritableWorkbook wwb;
		String[] strs = str.split("%%%%");
		String path = ((ServletContext)ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT)).getRealPath("/");
		
        try {  
        	//创建excel
            wwb = Workbook.createWorkbook(new FileOutputStream(path + "jsp\\score\\xls\\score.xls"));

            //创建格式
            WritableCellFormat wcf = new WritableCellFormat();
            wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
            wcf.setAlignment(Alignment.CENTRE);
            
            //创建sheet
            WritableSheet ws = wwb.createSheet("sheet", 0);
            ws.setRowView(1, 500);
            
            //表头
            ws.addCell(new Label(0, 0, "序号", wcf));
            ws.addCell(new Label(1, 0, "机构", wcf));
            ws.addCell(new Label(2, 0, "班级", wcf));
            ws.addCell(new Label(3, 0, "课件信息", wcf));
            ws.addCell(new Label(4, 0, "学员姓名", wcf));
            ws.addCell(new Label(5, 0, "课件成绩", wcf));
            ws.addCell(new Label(6, 0, "作业成绩", wcf));
            ws.addCell(new Label(7, 0, "总成绩", wcf));
            
            //内容
            int col = 0;
            int row = 1;
            for (int i = 0; i < strs.length; i++) {
            	if(i == 0) ws.addCell(new Label(col++, row, row+"", wcf));
            	ws.addCell(new Label(col++, row, strs[i], wcf));
            	if((i+1)%7 == 0){
            		col = 0;
            		row++;
            		if((i+1) != strs.length) ws.addCell(new Label(col++, row, row+"", wcf));
            	} 
			}

            wwb.write();
            wwb.close();
            
            return "success";
        } catch (Exception e){
        	e.printStackTrace();
        	
        	return "fail";
        }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
你可以使用Apache POI库来实现导出Excel文件中添加水印。下面是一个示例代码,演示如何在Excel文件中添加文本水印: ```java import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.*; public class ExcelWatermarkExample { public static void main(String[] args) throws Exception { // 创建工作簿 XSSFWorkbook workbook = new XSSFWorkbook(); // 创建工作表 XSSFSheet sheet = workbook.createSheet("Sheet1"); // 添加文本水印 addTextWatermark(sheet, "Confidential"); // 导出Excel文件 FileOutputStream fileOut = new FileOutputStream("output.xlsx"); workbook.write(fileOut); fileOut.close(); // 关闭工作簿 workbook.close(); } private static void addTextWatermark(XSSFSheet sheet, String watermarkText) { // 创建水印字体样式 Font font = sheet.getWorkbook().createFont(); font.setColor(IndexedColors.GREY.getIndex()); font.setFontHeightInPoints((short) 100); font.setBold(true); // 创建水印单元格样式 CellStyle cellStyle = sheet.getWorkbook().createCellStyle(); cellStyle.setRotation(-45); cellStyle.setFont(font); // 获取工作表的默认打印设置 XSSFPrintSetup printSetup = sheet.getPrintSetup(); printSetup.setLandscape(false); // 设置为纵向打印 // 创建水印单元格 XSSFCell watermarkCell = sheet.createRow(0).createCell(0); watermarkCell.setCellValue(watermarkText); watermarkCell.setCellStyle(cellStyle); // 设置水印单元格的位置和大小 sheet.addMergedRegion(new CellRangeAddress(0, sheet.getLastRowNum(), 0, sheet.getRow(0).getLastCellNum() - 1)); setCellSize(sheet, watermarkCell, 8); } private static void setCellSize(XSSFSheet sheet, XSSFCell cell, int zoom) { // 设置水印单元格所占区域的列宽和行高 sheet.setColumnWidth(cell.getColumnIndex(), (cell.getStringCellValue().length() + 2) * 256 * zoom); sheet.getRow(cell.getRowIndex()).setHeightInPoints(cell.getRow().getHeightInPoints() * zoom); } } ``` 此示例代码使用Apache POI库创建一个新的Excel文件并在第一个单元格中添加了文本水印。你可以根据需要修改水印的文本和样式。运行代码后,将在当前目录下生成一个名为"output.xlsx"的Excel文件,其中包含了添加了水印的表格。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

uikoo9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值