❶ struts2 中要在jsp页面上实现把数据库中的数据导成excel,在页面上点击导出时excel时,弹出下载保存框。
struts1我做过一个类似的。用jxl导入excel文件,获取里面的信息并修改,再将修改后的excel导出。struts2就不知道了。
❷ 如何将jsp页面表格另存为excel格式报表,或通过打印生成.xsl报表
看看下面的代码,应该对你有帮助:
<%@ page import="net.ExcelBean" %>
<%@ page import="java.io.*" %>
<%@ page import="net.createExcel.CreateExcelST" %>
<%@ page import="java.util.*" %>
<%@ page import="com.seipher.dwr.afterServiceDWR.FinanceDWR" %>
<%@ page import="net.TimeUtil" %>
<%@ page import="net.NumberUtil" %>
<%@ page import="com.seipher.pojo.afterService.DetachCharge" %>
<%@ page import="com.seipher.pojo.systemSet.SupplyTrader" %>
<%@ page import="com.seipher.pojo.afterService.Finance" %>
<%@ page import="com.seipher.dwr.afterServiceDWR.AbondDWR" %>
<%@ page import="com.seipher.pojo.afterService.Abond" %>
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<%
String supplyName = request.getParameter("supplyName1");
String usersName = request.getParameter("usersName1");
String startTimeA = request.getParameter("startTimeA1");
String endTimeA = request.getParameter("endTimeA1");
String pageNum = request.getParameter("pageNum1").toString();
ExcelBean excelBean = new ExcelBean();
CreateExcelST createExcel = new CreateExcelST();
excelBean.setPath("/two.xls");
List dataResult = new ArrayList();
List titleList = new ArrayList();
if (null == pageNum) return;
if (pageNum.equals("")) return;
AbondDWR abondDWR = new AbondDWR();
Map form = new HashMap();
form.put("supplyName", supplyName);
form.put("usersName", usersName);
form.put("startTimeA", startTimeA);
form.put("endTimeA", endTimeA);
form.put("pageNum", pageNum);
List result = abondDWR.selectAllByRows(Long.parseLong(pageNum), "1", form);
List list = (ArrayList) result.get(0);
titleList.add("供应商名称");
titleList.add("供应商编码");
titleList.add("起始时间");
titleList.add("截止时间");
titleList.add("开票金额");
titleList.add("操作时间");
titleList.add("操作人");
titleList.add("备注");
List dataList;
for (Object o : list) {
dataList = new ArrayList();
Abond abond = (Abond) o;
dataList.add(abond.getSupplyTrader().getName());
dataList.add(abond.getSupplyTrader().getCode());
if (null != abond.getStartTime()) {
String timeA = TimeUtil.getYYYY_MM_DD(abond.getStartTime());
if (null != timeA && !timeA.equals("") && !timeA.equals("1970-01-01")) {
dataList.add(timeA);
} else {
dataList.add("");
}
} else dataList.add("");
if (null != abond.getEndTime()) {
String timeA = TimeUtil.getYYYY_MM_DD(abond.getEndTime());
if (null != timeA && !timeA.equals("") && !timeA.equals("1970-01-01")) {
dataList.add(timeA);
} else {
dataList.add("");
}
} else dataList.add("");
dataList.add(abond.getMoney() + "");
if (null != abond.getOperateTime()) {
String timeA = TimeUtil.getYYYYMMDDHHMMSSLiuPC(abond.getOperateTime());
if (null != timeA && !timeA.equals("") && !timeA.equals("1970-01-01")) {
dataList.add(timeA);
} else {
dataList.add("");
}
} else dataList.add("");
dataList.add(abond.getUsersManage().getName());
dataList.add(abond.getMessages());
dataResult.add(dataList);
}
int[] width = {100, 40, 40, 40, 40, 40, 40, 40};
excelBean.setReportName(startTimeA + "到" + endTimeA + "开票信息查询");
excelBean.setDataList(dataResult);
excelBean.setSheetName(startTimeA + "到" + endTimeA + "开票信息查询");
excelBean.setTitleList(titleList);
excelBean.setColumnWidth(width);
excelBean.setFlag(false);
try {
createExcel.createExcelFile(excelBean);
} catch (Exception e) {
e.printStackTrace();
}
try {
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition", "attachment;filename=" + "kaipiaoxinxi" + ".xls");
FileInputStream finput = new FileInputStream(excelBean.getPath());
OutputStream output = response.getOutputStream();
BufferedInputStream buffin = new BufferedInputStream(finput);
BufferedOutputStream buffout = new BufferedOutputStream(output);
out.clear();
out = pageContext.pushBody();
byte[] buffer = new byte[4096];
int count = 0;
while ((count = buffin.read(buffer, 0, buffer.length)) > 0) {
buffout.write(buffer, 0, count);
}
buffin.close();
buffout.close();
finput.close();
output.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
File srcExcel = new File(excelBean.getPath());
srcExcel.delete();
}
%>
</body>
</html>
=============CreateExcelST.java======================
package net.createExcel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.hssf.util.HSSFColor;
import java.util.List;
import java.io.FileOutputStream;
import net.ExcelBean;
/**
* User: marlboro Date: 2008-2-15 Time: 10:15:38
*
* @author Marlboro
* @mailto [email protected]
*/
public class CreateExcelST {
private Log log = LogFactory.getFactory().getInstance(this.getClass().getName());
@SuppressWarnings("unchecked")
public void createExcelFile(ExcelBean excelBean) throws Exception {
// 创建工作薄
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(excelBean.getSheetName());
// 打印页面设置
HSSFPrintSetup ps = sheet.getPrintSetup();
sheet.setMargin(HSSFSheet.BottomMargin, 0.5);// 页边距
sheet.setMargin(HSSFSheet.LeftMargin, 0.1);
sheet.setMargin(HSSFSheet.RightMargin, 0.1);
sheet.setMargin(HSSFSheet.TopMargin, 0.5);
ps.setLandscape(true); // 打印方向,true:横向,false:纵向
ps.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE); // 纸张
// 设置列宽
this.setColumnWidth(sheet, excelBean.getColumnWidth());
// 标题栏设置字体
HSSFFont cellFontReport = wb.createFont();
cellFontReport.setFontHeightInPoints((short) 16); // 字号
cellFontReport.setBoldweight(HSSFFont.U_SINGLE); // 加粗
cellFontReport.setFontName("Courier New");
// 字段栏设置字体
HSSFFont cellFontColumn = wb.createFont();
cellFontColumn.setFontHeightInPoints((short) 12); // 字号
cellFontColumn.setBoldweight(HSSFFont.U_SINGLE); // 加粗
cellFontColumn.setFontName("Courier New");
cellFontColumn.setColor(HSSFFont.SS_NONE);
// 设置字体
HSSFFont cellFont = wb.createFont();
cellFont.setFontHeightInPoints((short) 10); // 字号
cellFont.setBoldweight(HSSFFont.U_SINGLE); // 加粗
cellFont.setFontName("Courier New");
//自定义颜色
HSSFPalette palette = wb.getCustomPalette();
palette.setColorAtIndex(HSSFColor.AQUA.index, (byte) 252, (byte) 254, (byte) 236);
// 设置标题栏单元格格式
HSSFCellStyle cellStyleReport = wb.createCellStyle();
cellStyleReport.setFont(cellFontReport);
cellStyleReport.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 左右居中
cellStyleReport.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 上下居中
cellStyleReport.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
cellStyleReport.setBorderLeft(HSSFCellStyle.BORDER_THIN); // 左边框
cellStyleReport.setBorderRight(HSSFCellStyle.BORDER_THIN); // 右边框
cellStyleReport.setBorderTop(HSSFCellStyle.BORDER_THIN); // 上边框
cellStyleReport.setWrapText(true);// 自动换行
cellStyleReport.setFillForegroundColor(HSSFColor.AQUA.index);
cellStyleReport.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
// 设置标题栏单元格格式
HSSFCellStyle cellStyleColumn = wb.createCellStyle();
cellStyleColumn.setFont(cellFontColumn);
cellStyleColumn.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 左右居中
cellStyleColumn.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 上下居中
cellStyleColumn.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
cellStyleColumn.setBorderLeft(HSSFCellStyle.BORDER_THIN); // 左边框
cellStyleColumn.setBorderRight(HSSFCellStyle.BORDER_THIN); // 右边框
cellStyleColumn.setBorderTop(HSSFCellStyle.BORDER_THIN); // 上边框
cellStyleColumn.setWrapText(true);// 自动换行
cellStyleColumn.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
cellStyleColumn.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
// 设置单元格格式
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setFont(cellFont);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 左右居中
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 上下居中
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); // 左边框
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); // 右边框
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); // 上边框
cellStyle.setWrapText(true);// 自动换行
List dataList = excelBean.getDataList();
if (null != dataList) {
// 报表的标题
List titleList = excelBean.getTitleList();
// 创建行 设置报表名称
HSSFRow rowReportName = sheet.createRow(0);
HSSFCell cellReportName = rowReportName.createCell((short) 0);
sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) (titleList.size() - 1)));
HSSFRichTextString reportString = new HSSFRichTextString(excelBean.getReportName());
cellReportName.setCellValue(reportString);
cellReportName.setCellStyle(cellStyleReport);
HSSFCell endReportName = rowReportName.createCell((short) (titleList.size() - 1));
endReportName.setCellStyle(cellStyleReport);
// 创建行
HSSFRow rowTitle = sheet.createRow(1);
for (int i = 0; i < titleList.size(); i++) {
String s_title = (String) titleList.get(i);
HSSFCell cellx_y = rowTitle.createCell((short) i);
HSSFRichTextString hssfRichTextString = new HSSFRichTextString(s_title);
// 单元格内容
cellx_y.setCellValue(hssfRichTextString);
// 单元格格式
cellx_y.setCellStyle(cellStyleColumn);
}
// 报表数据
for (int i = 0; i < dataList.size(); i++) {
HSSFRow row = sheet.createRow(i + 2);
List list_row = (List) dataList.get(i);
for (int j = 0; j < list_row.size(); j++) {
String strtmp = (String) list_row.get(j);
// String strtmp = list_row.get(j).toString();
if (" ".equals(strtmp)) {
strtmp = " ";
}
HSSFCell cell = row.createCell((short) j);
HSSFRichTextString hssfRichTextString = new HSSFRichTextString(strtmp);
cell.setCellValue(hssfRichTextString);
cell.setCellStyle(cellStyle);
}
}
}
// 另外一个标题
List otherTitleList = excelBean.getOtherTitleList();
if (otherTitleList != null) {
// 创建行
HSSFRow otherRowTitle = sheet.createRow(dataList.size() + 2);
for (int i = 0; i < otherTitleList.size(); i++) {
String s_title = (String) otherTitleList.get(i);
HSSFCell cellx_y = otherRowTitle.createCell((short) i);
HSSFRichTextString hssfRichTextString = new HSSFRichTextString(s_title);
cellx_y.setCellValue(hssfRichTextString); // 单元格内容
cellx_y.setCellStyle(cellStyle); // 单元格格式
}
// 另外的数据集
List otherDataList = excelBean.getOtherDataList();
// 报表数据
for (int i = 0; i < otherDataList.size(); i++) {
HSSFRow row = sheet.createRow(dataList.size() + 3 + i);
List list_row = (List) otherDataList.get(i);
for (int j = 0; j < list_row.size(); j++) {
String strtmp = (String) list_row.get(j);
if (" ".equals(strtmp)) {
strtmp = " ";
}
HSSFCell cell = row.createCell((short) j);
HSSFRichTextString hssfRichTextString = new HSSFRichTextString(strtmp);
cell.setCellValue(hssfRichTextString);
cell.setCellStyle(cellStyle);
}
}
}
try {
FileOutputStream fileOut = new FileOutputStream(excelBean.getPath());
log.debug("===FilePath>>>>>>>>>>>>>>>>>.===>>>>>>" + excelBean.getPath());
wb.write(fileOut);
fileOut.close();
} catch (Exception e) {
throw new Exception("文件已经打开,请关闭后再生成");
}
}
public void setColumnWidth(HSSFSheet sheet, int[] width) {
for (int i = 0; i < width.length; i++) {
sheet.setColumnWidth((short) i, (short) (width[i] * 100));
}
}
}
❸ jsp页面的数据怎么样导出到excel表格
方法一:
function saveCode(obj) {
var winname = window.open('', '_blank', 'top=10000');
var strHTML = document.all.tableExcel.innerHTML;
winname.document.open('text/html', 'replace');
winname.document.writeln(strHTML);
winname.document.execCommand('saveas','','excel.xls');
winname.close();
}
方法二:
// Excel导出2
/**
如果javaScript报“Automation 服务器不能创建对象”,则按下方解决。
打开Internet Explorer “工具”菜单栏中的“选项”一栏,单击“安全”栏中的“自定义级别”选项卡,
将第三项“对没有标记为安全的activex控件进行初始化和脚本运行”设置成“启用”即可。
*/
function exportExecl(tableId) {
var table=document.getElementById(tableId);
var oXL = new ActiveXObject("Excel.Application");
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
var sel=document.body.createTextRange();
sel.moveToElementText(table);
sel.select();
sel.execCommand("Copy");
oSheet.Paste();
oXL.Visible = true;
}
这里的tableId为表格的id
❹ jsp页面怎么导出excel
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script>
//全部打印到excel表
function AutomateExcelall()
{
var i,j;
// Start Excel and get Application object.
var oXL = new ActiveXObject("Excel.Application");
oXL.Visible = true;
// Get a new workbook.
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
// Add table headers going cell by cell.
oSheet.Cells(1, 1).Value = "编号";
oSheet.Cells(1, 2).Value = "姓名";
oSheet.Cells(1, 3).Value = "地址";
for(i=1;i<tblout.rows.length;i++)
{
for(j=1;j<tblout.rows(i).cells.length;j++)
{
oSheet.Cells(i+1, j).Value = tblout.rows(i).cells(j).innerText
}
}
oXL.Visible = true;
oXL.UserControl = true;
}
//选种打印到excel表
function AutomateExcel()
{
var i=0;
// var j=0; //i是行,j是列
var oXL = new ActiveXObject("Excel.Application");
oXL.Visible = true;
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
oSheet.Cells(1, 2).Value = "编号";
oSheet.Cells(1, 3).Value = "姓名";
oSheet.Cells(1, 4).Value = "地址";
var s=0;
for(i=1;i<tblout.rows.length+1;i++)
{
if(document.myform.mybox[i].checked==true)
{
s=s+1;
for(j=0;j<tblout.rows(i).cells.length;j++)
{
oSheet.Cells(s+1, j+1).Value = tblout.rows(i).cells(j).innerText
}
}
}
oXL.Visible = true;
oXL.UserControl = true;
}
//得到选种的复选框
function check()
{
var checkboxvalue=0;
for(var i=0;i<document.myform.mybox.length;i++)
{
if(document.myform.mybox[i].checked==true)
{
checkboxvalue=checkboxvalue+1;
}
}
document.myform.dayin.value=checkboxvalue;
}
</script>
</head>
<body>
<form action="" method="post" name="myform">
<table width="577" border="1" id="tblout">
<tr>
<td width="49" align="center">选项</td>
<td width="100" align="center">编号</td>
<td width="100" align="center">姓名</td>
<td width="101" align="center">地址</td>
<td colspan="3" align="center">操作</td>
</tr>
<tr>
<td align="left"><input type="checkbox" value="1" name="mybox" onclick="check()"/></td>
<td align="center">aa</td>
<td align="center">bb</td>
<td align="center">cc</td>
<td width="61" align="center">删除</td>
<td width="60" align="center">a</td>
<td width="60" align="center">修改</td>
</tr>
<tr>
<td align="left"><input type="checkbox" value="2" id="mybox" onclick="check()" /></td>
<td align="center">ee</td>
<td align="center">ff</td>
<td align="center">gg</td>
<td align="center">删除</td>
<td align="center">a</td>
<td align="center">修改</td>
</tr>
<tr>
<td><input type="checkbox" value="2" id="mybox" onclick="check()" /></td>
<td align="center">asdas</td>
<td align="center">fdsfsd</td>
<td align="center">sdfsdfsd</td>
<td align="center">删除</td>
<td align="center">a</td>
<td align="center">修改</td>
</tr>
<tr>
<td><input type="checkbox" value="2" id="mybox" onclick="check()" /></td>
<td align="center">fsdfs</td>
<td align="center">sdf/</td>
<td align="center">gsdfsdfg</td>
<td align="center">删除</td>
<td align="center">a</td>
<td align="center">修改</td>
</tr>
<tr>
<td><input type="checkbox" value="2" id="mybox" onclick="check()" /></td>
<td align="center">edsdse</td>
<td align="center">fsdasdaf</td>
<td align="center">gdasdag</td>
<td align="center">删除</td>
<td align="center">a</td>
<td align="center">修改</td>
</tr>
<tr>
<td><input type="checkbox" value="2" id="mybox" onclick="check()" /></td>
<td align="center">edsdse</td>
<td align="center">fsdasdaf</td>
<td align="center">gdasdag</td>
<td align="center">删除</td>
<td align="center">a</td>
<td align="center">修改</td>
</tr>
<tr>
<td><input type="checkbox" value="2" id="mybox" onclick="check()" /></td>
<td align="center">edsdse</td>
<td align="center">fsdasdaf</td>
<td align="center">gdasdag</td>
<td align="center">删除</td>
<td align="center">a</td>
<td align="center">修改</td>
</tr>
<tr>
<td><input type="checkbox" value="2" id="mybox" onclick="check()" /></td>
<td align="center">edsdse</td>
<td align="center">fsdasdaf</td>
<td align="center">gdasdag</td>
<td align="center">删除</td>
<td align="center">a</td>
<td align="center">修改</td>
</tr>
<tr>
<td><input type="checkbox" value="2" id="mybox" onclick="check()" /></td>
<td align="center">edsdse</td>
<td align="center">fsdasdaf</td>
<td align="center">gdasdag</td>
<td align="center">删除</td>
<td align="center">a</td>
<td align="center">修改</td>
</tr>
<tr>
<td><input type="checkbox" value="2" id="mybox" onclick="check()" /></td>
<td align="center">edsdse</td>
<td align="center">fsdasdaf</td>
<td align="center">gdasdag</td>
<td align="center">删除</td>
<td align="center">a</td>
<td align="center">修改</td>
</tr>
<tr>
<td><input type="checkbox" value="2" id="mybox" onclick="check()" /></td>
<td align="center">edsdse</td>
<td align="center">fsdasdaf</td>
<td align="center">gdasdag</td>
<td align="center">删除</td>
<td align="center">a</td>
<td align="center">修改</td>
</tr>
</table>
<input type="text" name="dayin" />
<input type="button" onclick="AutomateExcelall()" value="打印全部"/>
<input type="button" onclick="AutomateExcel()" value="选中全部"/>
</form>
</body>
</html>
❺ 如何把jsp页面导出到excel中
你是想将jsp中的数据导出到excel吧,有个关于java导出excel的jar包封装了这个功能,这个jar包你自己去网络下载下来就行,给你个示例,看看就能明白了。
package oa.common.utils;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import java.lang.reflect.Field;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
/***
* @author lsf
*/
public class ExportExcel {
/***************************************************************************
* @param fileName EXCEL文件名称
* @param listTitle EXCEL文件第一行列标题集合
* @param listContent EXCEL文件正文数据集合
* @return
*/
public final static String exportExcel(String fileName,String[] Title, List<Object> listContent) {
String result="系统提示:Excel文件导出成功!";
// 以下开始输出到EXCEL
try {
//定义输出流,以便打开保存对话框______________________begin
HttpServletResponse response=ServletActionContext.getResponse();
OutputStream os = response.getOutputStream();// 取得输出流
response.reset();// 清空输出流
response.setHeader("Content-disposition", "attachment; filename="+ new String(fileName.getBytes("GB2312"),"ISO8859-1"));
// 设定输出文件头
response.setContentType("application/msexcel");// 定义输出类型
//定义输出流,以便打开保存对话框_______________________end
/** **********创建工作簿************ */
WritableWorkbook workbook = Workbook.createWorkbook(os);
/** **********创建工作表************ */
WritableSheet sheet = workbook.createSheet("Sheet1", 0);
/** **********设置纵横打印(默认为纵打)、打印纸***************** */
jxl.SheetSettings sheetset = sheet.getSettings();
sheetset.setProtected(false);
/** ************设置单元格字体************** */
WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10,WritableFont.BOLD);
/** ************以下设置三种单元格样式,灵活备用************ */
// 用于标题居中
WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
wcf_center.setAlignment(Alignment.CENTRE); // 文字水平对齐
wcf_center.setWrap(false); // 文字是否换行
// 用于正文居左
WritableCellFormat wcf_left = new WritableCellFormat(NormalFont);
wcf_left.setBorder(Border.NONE, BorderLineStyle.THIN); // 线条
wcf_left.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
wcf_left.setAlignment(Alignment.LEFT); // 文字水平对齐
wcf_left.setWrap(false); // 文字是否换行
/** ***************以下是EXCEL开头大标题,暂时省略********************* */
//sheet.mergeCells(0, 0, colWidth, 0);
//sheet.addCell(new Label(0, 0, "XX报表", wcf_center));
/** ***************以下是EXCEL第一行列标题********************* */
for (int i = 0; i < Title.length; i++) {
sheet.addCell(new Label(i, 0,Title[i],wcf_center));
}
/** ***************以下是EXCEL正文数据********************* */
Field[] fields=null;
int i=1;
for(Object obj:listContent){
fields=obj.getClass().getDeclaredFields();
int j=0;
for(Field v:fields){
v.setAccessible(true);
Object va=v.get(obj);
if(va==null){
va="";
}
sheet.addCell(new Label(j, i,va.toString(),wcf_left));
j++;
}
i++;
}
/** **********将以上缓存中的内容写到EXCEL文件中******** */
workbook.write();
/** *********关闭文件************* */
workbook.close();
} catch (Exception e) {
result="系统提示:Excel文件导出失败,原因:"+ e.toString();
System.out.println(result);
e.printStackTrace();
}
return result;
}
}
❻ 鎬庝箞浠巎sp椤甸潰鐨勮〃鏍煎煎嚭鍒癊xcel
鏃犻潪鏄杩欐牱鐨勪竴涓杩囩▼銆傚厛閫氳繃鏁版嵁搴撴煡璇㈠嚭鏁版嵁锛屾斁鍒癓ist閲岋紝鐒跺悗鎶婅繖涓狶ist鍙戝線椤甸潰锛岀劧鍚庨亶鍘嗚繖涓狶ist鎶婃暟鎹鏄剧ず鍒拌繖涓琛ㄦ牸閲屻 瑕佹兂鎶婃暟鎹瀵煎嚭鍒癳xecel锛屽緢绠鍗曪紝鎶婇〉闈㈡帴鍙楃殑杩欎釜List鐢╦xl鍐欏埌Execel灏辫屼簡銆傚叿浣撳皢List瀵煎嚭鍒癊xecel鐨勭被濡備笅锛
package cms.;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import cms.utlis.DbUtils;
public class ToExecelByQuery {
//鏂规硶鎺ュ彈涓や釜鍙傛暟锛屼竴涓鏄痩ist锛岃繖涓鍦版柟鎴戠敤浜嗘硾鍨嬨傚彟涓涓鍙傛暟鏄疕ttpServletResponse response
public static void toExcelBy(List<AccessLog> list,HttpServletResponse response) {
// 鍒涘缓宸ヤ綔琛
WritableWorkbook book=null;
response.reset();
// 鍒涘缓宸ヤ綔娴
OutputStream os =null;
try {
// 璁剧疆寮瑰嚭瀵硅瘽妗
response.setContentType("application/DOWLOAD");
// 璁剧疆宸ヤ綔琛ㄧ殑鏍囬
response.setHeader("Content-Disposition",
"attachment; filename=****.xls");//璁剧疆鐢熸垚鐨勬枃浠跺悕瀛
os = response.getOutputStream();
// 鍒濆嬪寲宸ヤ綔琛
book = Workbook.createWorkbook(os);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
//浠ヤ笅鏄鎴戝仛鐨勫煎嚭鏃ュ織鐨勪竴涓妯$増
int nCount = list.size();
WritableSheet sheet = book.createSheet("璁块棶鏃ュ織", 0);
// 鐢熸垚鍚嶄负"鍟嗗搧淇℃伅"鐨勫伐浣滆〃锛屽弬鏁0琛ㄧず杩欐槸绗涓椤
int nI = 1;
// 琛ㄥ瓧娈靛悕
sheet.addCell(new jxl.write.Label(0, 0, "鏃ュ織缂栧彿"));
sheet.addCell(new jxl.write.Label(1, 0, "鐢ㄦ埛ID"));
sheet.addCell(new jxl.write.Label(2, 0, "鐢ㄦ埛濮撳悕"));
sheet.addCell(new jxl.write.Label(3, 0, "璁块棶鏃ユ湡"));
sheet.addCell(new jxl.write.Label(4, 0, "璁块棶鏃堕棿"));
sheet.addCell(new jxl.write.Label(5, 0, "鍚嶇墖ID"));
sheet.addCell(new jxl.write.Label(6, 0, "鍚嶇墖鍚嶇О"));
sheet.addCell(new jxl.write.Label(7, 0, "鍒涘缓鏃ユ湡"));
sheet.addCell(new jxl.write.Label(8, 0, "鏇存柊鏃ユ湡"));
// 灏嗘暟鎹杩藉姞
for(int i=1;i<list.size();i++){
sheet.addCell(new jxl.write.Label(0, i, list.get(i).toString()));
sheet.addCell(new jxl.write.Label(1, i, list.get(i).getUserId()));
sheet.addCell(new jxl.write.Label(2, i, list.get(i).getUsername()));
sheet.addCell(new jxl.write.Label(3, i, list.get(i).getCrtTim()));
sheet.addCell(new jxl.write.Label(4, i, list.get(i).getComplTime()));
sheet.addCell(new jxl.write.Label(5, i, list.get(i).getCopId()));
sheet.addCell(new jxl.write.Label(6, i, list.get(i).getFirstname()));
sheet.addCell(new jxl.write.Label(7, i, list.get(i).getCrtTim()));
sheet.addCell(new jxl.write.Label(8, i, list.get(i).getUpdTim()));
}
book.write();
book.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
澶т綋鎬濊矾灏辨槸杩欐牱鐨勶紝鍒蹇樹簡鍦ㄤ綘鐨勯」鐩涓瀵煎叆JXL蹇呰佺殑jar鍖咃紝杩欎釜鍖呭彨jxl.jar锛屼綘鍙浠ヤ笅杞戒竴涓銆傚笇鏈涜兘甯鍒颁綘锛屾㈣繋杩介棶銆傛湜閲囩撼锛
❼ java项目中怎么实现jsp页面Excel模板下载并弹框。
controller层关键代码:
@RequestMapping(value="/excel")
publicModelAndViewexportExcel()throwsException{
ModelAndViewmv=newModelAndView();
PageDatapd=newPageData();
pd=this.getPageData();
Map<String,Object>dataMap=newHashMap<String,Object>();
List<String>titles=newArrayList<String>();
titles.add("办事处");//1
titles.add("当日新增扫码商户(个)");//2
titles.add("当日交易笔数(笔)");//3
titles.add("当日交易金额");//4
titles.add("当日收益");//5
titles.add("累计新增扫码商户(个)");//6
titles.add("累计交易笔数(笔)");//7
titles.add("累计交易金额");//8
titles.add("累计收益");//9
dataMap.put("titles",titles);
Pagepage=newPage();
page.setPd(pd);
List<PageData>varOList=agencyService.list(page);
List<PageData>varList=newArrayList<PageData>();
for(inti=0;i<varOList.size();i++){
PageDatavpd=newPageData();
vpd.put("var1",varOList.get(i).get("AGENCYNAME").toString());//1
vpd.put("var2",varOList.get(i).get("TODAYINSTALL").toString());//2
vpd.put("var3",varOList.get(i).get("TODAYTRANS").toString());//3
vpd.put("var4",varOList.get(i).get("TODAYPRICE").toString());//4
vpd.put("var5",varOList.get(i).get("TODAYPAYMENT").toString());//5
vpd.put("var6",varOList.get(i).get("TOTALINSTALL").toString());//6
vpd.put("var7",varOList.get(i).get("TOTALTRANS").toString());//7
vpd.put("var8",varOList.get(i).get("TOTALPRICE").toString());//8
vpd.put("var9",varOList.get(i).get("TOTALPAYMENT").toString());//9
varList.add(vpd);
}
dataMap.put("varList",varList);
ObjectExcelViewerv=newObjectExcelView();
mv=newModelAndView(erv,dataMap);
returnmv;
}
POI生成EXCEL关键代码:
{
@SuppressWarnings("deprecation")
@Override
(Map<String,Object>model,
HSSFWorkbookworkbook,HttpServletRequestrequest,
HttpServletResponseresponse)throwsException{
//TODOAuto-generatedmethodstub
Datedate=newDate();
Stringfilename=Tools.date2Str(date,"yyyyMMddHHmmss");
HSSFSheetsheet;
HSSFCellcell;
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename="+filename+".xls");
sheet=workbook.createSheet("sheet1");
List<String>titles=(List<String>)model.get("titles");
intlen=titles.size();
HSSFCellStyleheaderStyle=workbook.createCellStyle();//标题样式
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
HSSFFontheaderFont=workbook.createFont(); //标题字体
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerFont.setFontHeightInPoints((short)11);
headerStyle.setFont(headerFont);
shortwidth=20,height=25*20;
sheet.setDefaultColumnWidth(width);
for(inti=0;i<len;i++){//设置标题
Stringtitle=titles.get(i);
cell=getCell(sheet,0,i);
cell.setCellStyle(headerStyle);
setText(cell,title);
}
sheet.getRow(0).setHeight(height);
HSSFCellStylecontentStyle=workbook.createCellStyle();//内容样式
contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
List<PageData>varList=(List<PageData>)model.get("varList");
intvarCount=varList.size();
for(inti=0;i<varCount;i++){
PageDatavpd=varList.get(i);
for(intj=0;j<len;j++){
Stringvarstr=vpd.getString("var"+(j+1))!=null?vpd.getString("var"+(j+1)):"";
cell=getCell(sheet,i+1,j);
cell.setCellStyle(contentStyle);
setText(cell,varstr);
}
}
}
}