❶ 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);
}
}
}
}