jsp页面内容导出到Excel中
JSP中导入导出Excel文件
JSP中导入导出Excel文件一.POI简介Jakarta POI 是apache的子项目,目标是处理ole2对象。
它提供了一组操纵Windows文档的Java API目前比较成熟的是HSSF接口,处理MS Excel(97-2002)对象。
它不象我们仅仅是用csv生成的没有格式的可以由Excel转换的东西,而是真正的Excel 对象,你可以控制一些属性如sheet,cell等等。
二.HSSF概况HSSF 是sHorrible SpreadSheet Format的缩写,也即“讨厌的电子表格格式”。
也许HSSF的名字有点滑稽,就本质而言它是一个非常严肃、正规的API。
通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。
HSSF 为读取操作提供了两类API:usermodel和eventusermodel,即“用户模型”和“事件-用户模型”。
前者很好理解,后者比较抽象,但操作效率要高得多。
三.开始编码1 .准备工作要求:JDK 1.4+POI开发包可以到 /dyn/closer.cgi/jakarta/poi/ 最新的POI工具包2 . EXCEL 结构HSSFWorkbook excel 文档对象介绍HSSFSheet excel的表单HSSFRow excel的行HSSFCell excel的格子单元HSSFFont excel字体HSSFName 名称HSSFDataFormat 日期格式HSSFHeader sheet头HSSFFooter sheet尾和这个样式HSSFCellStyle cell样式辅助操作包括HSSFDateUtil 日期HSSFPrintSetup 打印HSSFErrorConstants 错误信息表4 .可参考文档POI 主页:/poi/,初学者如何快速上手使用POI HSSF/poi/hssf/quick-guide.html 。
代码例子/user1/6749/archives/2005/18347.html里面有很多例子代码,可以很方便上手。
解决excel乱码
GB码,全称是GB2312-80《信息交换用汉字编码字符集 基本集》,1980年发布,是中文信息处理的国家标准,在大陆及海外使用简体中文的地区(如新加坡等)是强制使用的唯一中文编码。P-Windows3.2和苹果OS就是以GB2312为基本汉字编码, Windows 95/98则以GBK为基本汉字编码、但兼容支持GB2312。GB码共收录6763个简体汉字、682个符号,其中汉字部分:一级字3755,以拼音排序,二级字3008,以偏旁排序。该标准的制定和应用为规范、推动中文信息化进程起了很大作用。
GBK编码是中国大陆制订的、等同于UCS的新的中文编码扩展国家标准。GBK工作小组于1995年10月,同年12月完成GBK规范。该编码标准兼容GB2312,共收录汉字21003个、符号883个,并提供1894个造字码位,简、繁体字融于一库。
估计正是大陆制订这个关节出了问题,微软正是抓住自己的标准才会出现wps识别而excel不识别的情况。看来标准之争是不得不争啊。
12.</TR>
13.</TABLE>
14.</body>
15.</HTML>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
//解释,为何wps打开正常,office-excel打开乱码
第二步,在该JSP页面头部设置response的ContentType为Excel格式
引用
<% response.setContentType("application/vnd.ms-excel;charset=GBK"); %>
jsp 中poi 实现导入导出excel
1.excel导入数据导入时候注意数字类型和字符类型的区别,数字类型要在excel中设置数字类型,对应数据库中也应该建立对应类型<%@ page import="com.guanri.database.*,java.util.*,com.guanri.util.*,com.jspsmart.upload.*" contentType="text/html; charset=GBK" %><%@ pageimport="java.util.*,java.io.*,org.apache.poi.poifs.filesystem.*,ermodel.*" %><jsp:include page="/admin/checkLogin.jsp"/><%String result = "";String contracId = "";String projectname = "";double projectscale = 0;String projecttype="";String projectconunit="";double designtime = 0;String designphase = "";double completedtime = 0;String participants = "";String positionofpro = "";String dutiesas = "";int inum = 0;int unum = 0;int rnum = 0;int snum = 0;String rmstr = "";Table tb = new Table();Vector vc = null;Hashtable rows = new Hashtable();String sql = "";if(request.getMethod().equalsIgnoreCase("POST")) {String sdir = "/download/xlsdir/"; //文件保存目录String filesep=System.getProperty("file.separator");String ssdir = filesep+"download"+filesep+"xlsdir"+filesep;Calendar c = Calendar.getInstance();String fname = c.getTimeInMillis()+".xls";String sfname = sdir + fname;String ss = "xls"; //支持的文件后缀名try{SmartUpload su = new SmartUpload();su.initialize(pageContext);su.setAllowedFilesList(ss);su.upload();com.jspsmart.upload.File file = su.getFiles().getFile(0);if(!file.isMissing()){file.saveAs(sfname);// System.out.println(application.getRealPath("/")+ssdir+fname );FileInputStream finput = new FileInputStream(application.getRealPath("/")+ssdir+fname );//设定FileINputStream读取Excel档POIFSFileSystem fs = new POIFSFileSystem( finput );HSSFWorkbook wb = new HSSFWorkbook(fs);HSSFSheet sheet = wb.getSheetAt(0);//读取第一个工作表,宣告其为sheetfinput.close();HSSFRow row=null;//宣告一列HSSFCell cell=null;//宣告一个储存格short i=0;short y=0;//以巢状迴圈读取所有储存格资料System.out.println("sheet.getLastRowNum()="+sheet.getLastRowNum());for (i=1;i<=sheet.getLastRowNum();i++){row=sheet.getRow(i);for (y=1;y<=row.getLastCellNum();y++){cell=row.getCell(y);switch(y){case 1: //合同号if(cell!=null){contracId=(cell.getStringCellValue()).trim();}break;case 2: //项目名称if(cell!=null){projectname=(cell.getStringCellValue()).trim();}break;case 3: //项目规模if(cell!=null){projectscale=cell.getNumericCellValue();}break;case 4: //项目类型if(cell!=null){projecttype=(cell.getStringCellValue()).trim();}break;case 5: //项目建设单位if(cell!=null){projectconunit=(cell.getStringCellValue()).trim();}break;case 6: //设计时间if(cell!=null){designtime=cell.getNumericCellValue();}break;case 7: //设计阶段if(cell!=null){designphase=(cell.getStringCellValue()).trim();}break;case 8: //竣工时间if(cell!=null){completedtime=cell.getNumericCellValue();}break;case 9: //参与人姓名if(cell!=null){participants=(cell.getStringCellValue()).trim();}break;case 10: //担任项目职务if(cell!=null){positionofpro=(cell.getStringCellValue()).trim();}break;case 11: //担任职责if(cell!=null){dutiesas=(cell.getStringCellValue()).trim();}break;}}sql = "insert into hy_pro_briefinfo(contracId,projectname,projectscale,projecttype,projectconunit,designtime,designphase,completedtime, participants,positionofpro,dutiesas) ";sql+="values('"+contracId+"','"+projectname+"','"+projectscale+"','"+projecttype+"','"+projectconunit+"','"+(int)designti me+"','"+designphase+"','"+(int)completedtime+"','"+participants+"','"+positionofpro+"','"+dutiesas+"')"; //System.out.println(sql);snum = tb.update(sql);if(snum<=0){++rnum;rmstr = rmstr + ",";}else{++inum;}mit();tb.setCommit(true);// System.out.println("result="+result);//System.out.println("snum="+snum +"inum="+inum);}result = "共成功上传"+(inum+unum)+" 条记录,其中新增"+inum+" 条,更新"+unum+" 条;失败"+rnum+" 条("+rmstr+" )";// System.out.println(result);java.io.File f = new java.io.File(application.getRealPath("/")+ssdir+fname);f.delete();}else{result = "上传文件失败";}}catch(Exception ex){ex.printStackTrace();java.io.File f = new java.io.File(application.getRealPath("/")+ssdir+fname);//f.delete();// result = ex.getMessage();if(result.indexOf("1010")>0){result = "文件格式不对!只支持"+ss+"格式文件";}if("You cannot get a numeric value from a String based cell".equals(result)){result = "格式错误:在数字单元格中存在非数字!第"+(unum+inum+1)+"条记录出错";}}//finally{// response.sendRedirect("pro_per_info.jsp");// }}%><jsp:include page="/admin/BodyStart" />Ext.MessageBox.alert("提示",'<%=result %>');setTimeout("window.location.href='pro_per_info.jsp'", 1000);<jsp:include page="/admin/BodyEnd" />2.excel导出数据导出的时候注意中文编码的问题response.reset();response.setContentType("application/vnd.ms-excel");必须按照先后顺序书写<%@ page language="java"import="com.guanri.database.*,java.util.*,com.guanri.util.*,com.jspsmart.upload.*" contentType="text/html; charset=gb2312" pageEncoding="gb2312"%><%@ page import="java.util.*,java.io.*,ermodel.*" %><%//response.setContentType("application/msexcel;charset=utf-8" );//response.setContentType("text/html;charset=utf-8");response.reset();response.setContentType("application/vnd.ms-excel");request.setCharacterEncoding("gb2312");String workSheetName = "pro_info.xls";response.setHeader("Content-disposition", "attachment; filename="+workSheetName);//WriteExcel we=new WriteExcel();//System.out.println("文件生成");//we.getExcel("steet1",response.getOutputStream());HSSFWorkbook workbook = new HSSFWorkbook(); //产生工作簿对象HSSFSheet sheet = workbook.createSheet(); //产生工作表对象sheet.setDefaultRowHeight((short) 10);sheet.setDefaultColumnWidth((short) 20);sheet.setColumnWidth((short) 4, (short) 10000);// 单位workbook.setSheetName(0,"firstSheet");// 设置字体HSSFFont font = workbook.createFont();// font.setFontHeightInPoints(( short ) 20 ); // 字体高度// font.setColor(HSSFFont.COLOR_RED); // 字体颜色font.setFontName( " 黑体" ); // 字体font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); // 宽度// font.setItalic( true ); // 是否使用斜体// font.setStrikeout(true); // 是否使用划线// 设置单元格类型HSSFCellStyle cellStyle = workbook.createCellStyle();cellStyle.setFont(font);cellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 水平布局:居左边cellStyle.setWrapText( true );HSSFRow row = sheet.createRow((short)0);//产生第一行HSSFCell cell = row.createCell((short) 0);//产生第一个单元格 cell.setCellType(HSSFCell.CELL_TYPE_STRING);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("本公司项目统计信息");row = sheet.createRow((short) 1);//产生第二行cell = row.createCell((short) 0);//产生第一个单元格cell.setCellType(HSSFCell.CELL_TYPE_STRING);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("序号");cell = row.createCell((short) 1);//产生第二个单元格cell.setCellType(HSSFCell.CELL_TYPE_STRING);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("姓名");cell = row.createCell((short) 2);//产生第二个单元格cell.setCellType(HSSFCell.CELL_TYPE_STRING);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("项目名称");cell = row.createCell((short) 3);//产生第二个单元格cell.setCellType(HSSFCell.CELL_TYPE_STRING);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("项目类型");cell = row.createCell((short) 4);//产生第二个单元格cell.setCellType(HSSFCell.CELL_TYPE_STRING);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("项目规模");cell = row.createCell((short) 5);//产生第二个单元格cell.setCellType(HSSFCell.CELL_TYPE_STRING);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("担任项目职务");cell = row.createCell((short) 6);//产生第二个单元格cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue("设计时间");cell = row.createCell((short) 7);//产生第二个单元格 cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue("设计阶段");cell = row.createCell((short) 8);//产生第二个单元格 cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue("项目建设单位");cell = row.createCell((short) 9);//产生第二个单元格 cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue("竣工时间");cell = row.createCell((short) 10);//产生第二个单元格 cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue("专项设计");cell = row.createCell((short) 11);//产生第二个单元格 cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue("直属专业领导");Table tb = new Table();Vector vc = null;Hashtable rows=new Hashtable();String sql = "";sql = "select * from hy_pro_briefinfo where 1=1"; sql = sql + " order by participants";vc = tb.getContent(sql);// System.out.println(sql);// String result = "";int order=0;String contracId = "";String projectname = "";String projectscale = "";String projecttype="";String projectconunit="";double designtime = 0;String designphase = "";double completedtime = 0;String participants = "";String positionofpro = "";String dutiesas = "";String leader="";int iRow=2;String info="";String pername="";int num=1;for(int i=0;i<vc.size();i++){rows = (Hashtable)vc.get(i);order=i+1;participants=(String)rows.get("participants");if(!pername.equals(participants)){pername=participants;num=1;}else{num++;}// System.out.println("participants="+participants);projectname=(String)rows.get("projectname");projecttype=(String)rows.get("projecttype");// System.out.println("projectname="+projectname);positionofpro=(String)rows.get("positionofpro");// System.out.println("positionofpro="+positionofpro);designtime=((Integer)rows.get("designtime")).intValue();projectscale=(Double)rows.get("projectscale")+"";// System.out.println("designtime="+designtime);designphase=(String)rows.get("designphase");// System.out.println("designphase="+designphase);projectconunit=(String)rows.get("projectconunit");// System.out.println("projectconunit="+projectconunit);completedtime=((Integer)rows.get("completedtime")).intValue(); // System.out.println("completedtime="+completedtime);dutiesas=(String)rows.get("dutiesas");// System.out.println("dutiesas="+dutiesas);row= sheet.createRow((short)iRow);;for(int j=1;j<=11;j++){cell = row.createCell((short)(j-1));cell.setCellStyle(cellStyle); // 设置单元格样式cell.setCellType(HSSFCell.CELL_TYPE_STRING);cell.setEncoding(HSSFCell.ENCODING_UTF_16);switch(j-1){case 0: //编号info=num+"";break;case 1: //姓名info=participants+"";break;case 2: //项目名称info=projectname+"";break;case 3: //项目类型info=projecttype+"";break;case 4: //面积info="建筑面积:"+projectscale+"平方米";break;case 5: //担任项目职务info=positionofpro+"";break;case 6: //设计时间info=designtime+"";info=info.substring(0,info.indexOf("."));break;case 7: //设计阶段info=designphase+"";break;case 8: //施工单位info=projectconunit+"";break;case 9: //竣工时间info=completedtime+"";info=info.substring(0,info.indexOf("."));if("0".equals(info)){info="";}break;case 10: //专项设计info=dutiesas+"";break; //直属专业领导case 11:info=leader+"";break;}//System.out.println("info="+info);cell.setCellValue(info);}iRow++;}OutputStream output=response.getOutputStream();output.flush();workbook.write(response.getOutputStream());output.close();%>。
jsp导出word,excel实例
<!--合并-->
xlsheet.Range(xlsheet.Cells(1,1),xlsheet.Cells(1,7)).mergecells=true;
xlsheet.Range(xlsheet.Cells(1,1),xlsheet.Cells(1,7)).value="发卡记录";
小米_枫|| 退出JAVA程序员之点点滴滴从此开始程序员d不归路... 主页博客相册|个人档案|好友|i贴吧 查看文章
JS操作Word和Excel的方法[转]2009-09-17 11:271.保存html页面到word
***************************************************************************************
}
}
</script>
2、拷贝table1内的内容到word
<script language="javascript">
function OpenWord(){//导出word
Layer1.style.border=0;
ExcelSheet = new ActiveXObject('Word.Application');
sel.select();
sel.execCommand("Copy");
Range.Paste();
word .Application.Visible = true;
alert("s");
JSP页面中导出Excel文件及其中文乱码的解决办法
JSP页面中导出Exc el文件及其中文乱码的解决办法Web应用导出Ex cel报表的简单实现(HTML)在Web应用中,很多数据经常要导出成Exc el文档。
用专门的生成真正的E xcel文档的方式比较复杂,不太好用。
所以经常用一种简单的方式来实现,即将报表保存为HTM L格式,然后用Exc el打开。
实现方式:第一步,用JSP实现HTM L版本的报表第二步,在该JS P页面头部设置res ponse的Cont entTy pe为Ex cel格式<%respo nse.s etCon tentT ype("appli catio n/vnd.ms-e xcel;chars et=GB K");%>中文问题:查看源代码时发现J SP文件中写死的中文为乱码,则在JSP文件头部添加一行<%@ pag e con tentT ype="text/html; char set=g b2312" %>查看源代码时发现文字为中文,但是用Exc el打开为乱码则在<html>与<hea d>中加入<met a htt p-equ iv="C onten t-Typ e" co ntent="tex t/htm l; ch arset=GBK">用S ervle t实现也是类似的处理方法。
实现样例:Test.jsp<%@ p age c onten tType="tex t/htm l; ch arset=GBK" %><% res ponse.setC onten tType("app licat ion/v nd.ms-exce l;cha rset=GBK"); %><HTML><me ta ht tp-eq uiv="Conte nt-Ty pe" c onten t="te xt/ht ml; c harse t=GBK"><h ead><title>Test</tit le></head><bod y><T ABLEborde rColo r=#111111cellS pacin g=0 c ellPa dding=2 wi dth=1200 a lign=cente r bor der=1><TR><TD alig n=mid dle w idth="10%" heig ht=20 rowS pan=2>项目</TD><TD a lign=middl e wid th="2%" he ight=20 ro wSpan=2>计量单位 </TD><TD al ign=m iddle widt h="4%" hei ght=20>满期赔付率 </TD></TR></TAB LE></body></H TML>Web应用导出Exc el报表的简单实现(HTML)在Web应用中,很多数据经常要导出成E xcel文档。
JS导出Table为excel的三种可行方法
JS导出Table为excel的三种可行方法[html] view plain copy1.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"2."/TR/xhtml1/DTD/xhtml1-transitional.dtd">3.<html xmlns="/1999/xhtml">4.<head>5.<meta http-equiv="Content-Type"content="text/html; charset=gb2312"/>6.<title>WEB页面导出为EXCEL文档的方法</title>7.</head>8.<body>9.<table id="tableExcel"width="100%"border="1"cellspa cing="0"cellpadding="0">10.<tr>11.<td colspan="5"align="center">WEB页面导出为EXCEL文档的方法</td>12.</tr>13.<tr>14.<td>列标题1</td>15.<td>列标题2</td>16.<td>列标题3</td>17.<td>列标题4</td>18.<td>列标题5</td>19.</tr>20.<tr>21.<td>aaa</td>22.<td>bbb</td>23.<td>ccc</td>24.<td>ddd</td>25.<td>eee</td>26.</tr>27.<tr>28.<td>AAA</td>29.<td>BBB</td>30.<td>CCC</td>31.<td>DDD</td>32.<td>EEE</td>33.</tr>34.<tr>35.<td>FFF</td>36.<td>GGG</td>37.<td>HHH</td>38.<td>III</td>39.<td>JJJ</td>40.</tr>41.</table>42.<input type="button"onclick="javascript:method1('ta bleExcel');"value="第一种方法导入到EXCEL">43.<input type="button"onclick="javascript:method2('ta bleExcel');"value="第二种方法导入到EXCEL">44.<input type="button"onclick="javascript:getXlsFrom Tbl('tableExcel',null);"value="第三种方法导入到EXCEL">45.<SCRIPT LANGUAGE="javascript">46.function method1(tableid) {//整个表格拷贝到EXCEL 中47.var curTbl = document.getElementById(tableid);48.var oXL = new ActiveXObject("Excel.Application");49.//创建AX对象excel50.var oWB = oXL.Workbooks.Add();51.//获取workbook对象52.var oSheet = oWB.ActiveSheet;53.//激活当前sheet54.var sel = document.body.createTextRange();55.sel.moveToElementText(curTbl);56.//把表格中的内容移到TextRange中57.sel.select();58.//全选TextRange中内容59.sel.execCommand("Copy");60.//复制TextRange中内容61.oSheet.Paste();62.//粘贴到活动的EXCEL中63.oXL.Visible = true;64.//设置excel可见属性65.}66.function method2(tableid) //读取表格中每个单元到EXCEL中67.{68.var curTbl = document.getElementById(tableid);69.var oXL = new ActiveXObject("Excel.Application");70.//创建AX对象excel71.var oWB = oXL.Workbooks.Add();72.//获取workbook对象73.var oSheet = oWB.ActiveSheet;74.//激活当前sheet75.var Lenr = curTbl.rows.length;76.//取得表格行数77.for (i = 0; i <Lenr; i++)78.{79.var Lenc = curTbl.rows(i).cells.length;80.//取得每行的列数81.for (j = 0; j <Lenc; j++)82.{83.oSheet.Cells(i + 1, j + 1).value = curTbl.rows(i).cells(j).i nnerText;84.//赋值85.}86.}87.oXL.Visible = true;88.//设置excel可见属性89.}90.function getXlsFromTbl(inTblId, inWindow) {91.try {92.var allStr = "";93.var curStr = "";94.//alert("getXlsFromTbl");95.if (inTblId != null && inTblId != "" && inTblId != "null" ) {96.curStr = getTblData(inTblId, inWindow);97.}98.if (curStr != null) {99.allStr += curStr;100.}101.else {102.alert("你要导出的表不存在!");103.return;104.}105.var fileName = getExcelFileName();106.doFileExport(fileName, allStr);107.}108.catch(e) {109.alert("导出发生异常:" + + "->" + e.description + "!");110.}111.}112.function getTblData(inTbl, inWindow) {113.var rows = 0;114.//alert("getTblData is " + inWindow);115.var tblDocument = document;116.if (!!inWindow && inWindow != "") {117.if (!document.all(inWindow)) {118.return null;119.}120.else {121.tblDocument = eval(inWindow).document;122.}123.}124.var curTbl = tblDocument.getElementById(inTbl);125.var outStr = "";126.if (curTbl != null) {127.for (var j = 0; j <curTbl.rows.length; j++) {128.//alert("j is " + j);129.for (var i = 0; i <curTbl.rows[j].cells.length; i++) {130.//alert("i is " + i);131.if (i == 0 && rows > 0) {132.outStr += " \t";133.rows -= 1;134.}135.outStr += curTbl.rows[j].cells[i].innerText + "\t";136.if (curTbl.rows[j].cells[i].colSpan > 1) {137.for (var k = 0; k <curTbl.rows[j].cells[i].colSpan - 1; k ++) {138.outStr += " \t";139.}140.}141.if (i == 0) {142.if (rows == 0 && curTbl.rows[j].cells[i].rowSpan > 1) {143.rows = curTbl.rows[j].cells[i].rowSpan - 1;144.}145.}146.}147.outStr += "\r\n";148.}149.}150.else {151.outStr = null;152.alert(inTbl + "不存在!");153.}154.return outStr;155.}156.function getExcelFileName() {157.var d = new Date();158.var curYear = d.getYear();159.var curMonth = "" + (d.getMonth() + 1);160.var curDate = "" + d.getDate();161.var curHour = "" + d.getHours();162.var curMinute = "" + d.getMinutes();163.var curSecond = "" + d.getSeconds();164.if (curMonth.length == 1) {165.curMonth = "0" + curMonth;166.}167.if (curDate.length == 1) {168.curDate = "0" + curDate;169.}170.if (curHour.length == 1) {171.curHour = "0" + curHour;172.}173.if (curMinute.length == 1) {174.curMinute = "0" + curMinute;175.}176.if (curSecond.length == 1) {177.curSecond = "0" + curSecond;178.}179.var fileName = "leo_zhang" + "_" + curYear + curMont h + curDate + "_"180.+ curHour + curMinute + curSecond + ".csv";181.//alert(fileName);182.return fileName;183.}184.function doFileExport(inName, inStr) {185.var xlsWin = null;186.if (!!document.all("glbHideFrm")) {187.xlsWin = glbHideFrm;188.}189.else {190.var width = 6;191.var height = 4;192.var openPara = "left=" + (window.screen.width / 2 - width / 2)193.+ ",top=" + (window.screen.height / 2 - height / 2) 194.+ ",scrollbars=no,width=" + width + ",height=" + heig ht;195.xlsWin = window.open("", "_blank", openPara);196.}197.xlsWin.document.write(inStr);198.xlsWin.document.close();199.xlsWin.document.execCommand('Saveas', true, inNam e);200.xlsWin.close();201.}202.</SCRIPT>203.</body>204.</html>。
js导出Excel表格-方法一
/* * 默认转换实现函数,如果需要其他功能,需自行扩展
* 参数:
* tableID : HTML中Table对象id属性值
* 详细用法参见以下 TableToExcel 对象定义
myWorkbook.Worksheets(2).Delete();
jXls.DisplayAlerts = true;
myWorksheet = myWorkbook.ActiveSheet;
var readRow = 0, readCol = 0;var totalRow = 0, totalCol = 0;
var tabNum = 0;
//设置行高、列宽
if(this.columnWidth != -1)
myWorksheet.Columns.ColumnWidth = this.columnWidth;
else
myWorksheet.Columns.ColumnWidth = 7;
myExcelCell2 = myWorksheet.Cells(readRow + myCellRowSpan - 1, readCol + myCellColSpan - 1);
myWorksheet.Range(myExcelCell, myExcelCell2).Merge();
if (obj[x].id == this.tableID) {
ቤተ መጻሕፍቲ ባይዱ tabNum = x;
totalRow = obj[x].rows.length;
jsp页面显示数据导出到excel表中
jsp页面显示数据导出到excel表中发表时间:2007-01-26内容来源:CSDN作者:佚名Excel报表的方法,一个过於简单,一个只能用於window平台(因为使用jdbc-odbc bridge),且无法使用到Excel内部的各种公式或是方法,因此,今天介绍一个apache出的元件叫POI,它可以在UNIX或window平台处理word或Excel档案,而不需要依靠window的com,并且可设定储存格格式、列印格式等等;今天我来介绍其中有关资料读取、新增、修改及删除的功能,若各位网友研究好其他的功能,麻烦Email给我(ljj@.tw),分享给大家!一、需要用的档案:jakarta-poi-1.8.0-dev-20020917.jar几乎每天都有1.8.0的最新版(但非正式版),正式的版本是1.5.0/builds/jakarta-poi/nightly/将档案复制到classpath所指到的地方二、有兴趣的朋友可以参考/poi/三、先建立一个叫做book1.xls的Excel档,内容如下----------------------------------项目单价数量合计CPU7000535000硬碟250025000记忆体160034800----------------------------------其中合计的栏位是设定公式,单价*数量四、资料读取範例<%@ page contentType="text/html;charset=MS950" import="java.util.*,java.io.*" %><%@ page import="org.apache.poi.poifs.filesystem.*,ermodel.*" %><html><head><meta http-equiv="Content-Type" content="text/html; charset=MS950"><title>读取Excel档案</title></head><body><table border="1" width="100%"><%FileInputStream finput = new FileInputStream(application.getRealPath("/")+"book1.xls" );//设定FileINputStream读取Excel档POIFSFileSystem fs = new POIFSFileSystem( finput );HSSFWorkbook wb = new HSSFWorkbook(fs);HSSFSheet sheet = wb.getSheetAt(0);//读取第一个工作表,宣告其为sheetfinput.close();HSSFRow row=null;//宣告一列HSSFCell cell=null;//宣告一个储存格short i=0;short y=0;//以巢状迴圈读取所有储存格资料for (i=0;i<=sheet.getLastRowNum();i++){out.println("<tr>");row=sheet.getRow(i);for (y=0;y<row.getLastCellNum();y++){cell=row.getCell(y);out.print("<td>");//判断储存格的格式switch ( cell.getCellType() ){case HSSFCell.CELL_TYPE_NUMERIC:out.print(cell.getNumericCellValue());//getNumericCellValue()会回传double值,若不希望出现小数点,请自行转型为intbreak;case HSSFCell.CELL_TYPE_STRING:out.print( cell.getStringCellValue());break;case HSSFCell.CELL_TYPE_FORMULA:out.print(cell.getNumericCellValue());//读出公式储存格计算後的值//若要读出公式内容,可用cell.getCellFormula()break;default:out.print( "不明的格式");break;}out.println("</td>");}out.println("</tr>");}%></table></body></html>五、资料新增範例<%@ page contentType="text/html;charset=MS950" import="java.util.*,java.io.*" %><%@ page import="org.apache.poi.poifs.filesystem.*,ermodel.*" %><html><meta http-equiv="Content-Type" content="text/html; charset=MS950"><title>插入资料至Excel档案</title></head><body><%FileInputStream finput = new FileInputStream(application.getRealPath("/")+"book1.xls" ); //设定FileINputStream读取Excel档POIFSFileSystem fs = new POIFSFileSystem( finput );HSSFWorkbook wb = new HSSFWorkbook(fs);HSSFSheet sheet = wb.getSheetAt(0);//读取第一个工作表,宣告其为sheetfinput.close();HSSFRow row=null;//宣告一列HSSFCell cell=null;//宣告一个储存格short i=4;row=sheet.createRow(i);//建立一个新的列,注意是第五列(列及储存格都是从0起算)cell=row.createCell((short)0);cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设定这个储存格的字串要储存双位元cell.setCellValue("显示卡");cell=row.createCell((short)1);cell.setCellValue(1700);cell=row.createCell((short)2);cell.setCellValue(8);cell=row.createCell((short)3);//设定这个储存格为公式储存格,并输入公式cell.setCellFormula("B"+(i+1)+"*C"+(i+1));try{FileOutputStream fout=new FileOutputStream(application.getRealPath("/")+"book1.xls");wb.write(fout);//储存fout.close();out.println("储存成功<a href='book1.xls'>book1.xls</a>");}catch(IOException e){out.println("产生错误,错误讯息:"+e.toString());}%></html>六、资料删除、修改範例<%@ page contentType="text/html;charset=MS950" import="java.util.*,java.io.*" %><%@ page import="org.apache.poi.poifs.filesystem.*,ermodel.*" %><html><head><meta http-equiv="Content-Type" content="text/html; charset=MS950"><title>删除、修改资料至Excel档案</title></head><body><%FileInputStream finput = new FileInputStream(application.getRealPath("/")+"book1.xls" ); //设定FileINputStream读取Excel档POIFSFileSystem fs = new POIFSFileSystem( finput );HSSFWorkbook wb = new HSSFWorkbook(fs);HSSFSheet sheet = wb.getSheetAt(0);//读取第一个工作表,宣告其为sheetfinput.close();HSSFRow row=null;//宣告一列HSSFCell cell=null;//宣告一个储存格row=sheet.getRow((short)4);//取出第五列if (row!=null)sheet.removeRow(row);//先侦测第五列存不存在,若在的话将第五列删除row=sheet.getRow((short)3);//取出第四列cell=row.getCell((short)2);//取出第三个储存格cell.setCellValue(7);//设定该储存格值为7cell=row.getCell((short)3);cell.setCellFormula(cell.getCellFormula());//上两行为取出公式储存格,并重新计算(因为刚才更新过计算公式的值)//如果不做,公式计算後的值不会更新try{FileOutputStream fout=new FileOutputStream(application.getRealPath("/")+"book1.xls");wb.write(fout);//储存fout.close();out.println("储存成功<a href='book1.xls'>book1.xls</a>");}catch(IOException e){out.println("产生错误,错误讯息:"+e.toString());}%></body></html>/gqm1982/archive/2007/01/25/1493229.aspx本篇文章来源于站长资讯网原文链接:/0701/jsp-116977784110490.html。
jsp输出如下四行五列的表格
竭诚为您提供优质文档/双击可除jsp输出如下四行五列的表格篇一:jsp表格增加行//增加行functionaddRow(){//添加一行varmaintable=document.getelementbyid("yourtable");varnewtr=maintable.insertRow();varnewtd0=newtr.insertcell();varnewtd1=newtr.insertcell();//设置列内容和属性newtd0.innerhtml=""newtd1.innerhtml="";}//删除行functiondelRow(obj){vartr=this.getRowobj(obj);if(tr!=null){tr.parentnode.removechild(tr);}else{thrownewerror("thegivenobjectisnotcontainedbythetab le");}}利用js来动态创建表格有两种格式,appendchild()和insertRow、insertcell()。
但第一种有可能在ie上有问题,所以推荐使用第二种。
1、insertRow(index):index从0开始这个函数将新行添加到index的那一行前,比如insertRow(0),是将新行添加到第一行之前。
默认的insertRow()函数相当于insertRow(-1),将新行添加到表的最后。
一般我们在使用的时候都是:objtable.insertRow(objtable.rows.length)就是为表格objtable在最后新增一行。
insertcell()和insertRow的用法相同。
2、deleteRow(index):index从0开始删除指定位置的行,要传入的参数:index是行在表格中的位置,可以下面的方法取得然后去删除:varrow=document.getelementbyid("行的id");varindex=row.rowindex;//有这个属性objtable.deleteRow(index);在使用过程中,删除表格的行的时候,如果删除了某一行,那么表格行数是马上就变化的,rows.length总是在变小,所以如果你要删除表格的所有行:functionremoveallRow(){varobjtable=document.getelementbyid("mytable");varlength=objtable.rows.length;for(vari=1;i objtable.deleteRow(i);}}3、setattribute()方法,动态设置单元格与行的属性格式如下:setattribute(属性,属性值)varobjmytable=document.getelementbyid("mytable");objmytable.setattribute("border",1);//为表格设置边框为1在使用的时候遇到一个设置样式的问题,不能用setattribute("class","inputbox1");而应该使用setattribute("classname","inputbox1"),4、创建表格了解了行与单元格的增删那就可以创建表格了。
几种前端json导出excel方法
⼏种前端json导出excel⽅法第⼀种导出excel⽆需⾃⼰设置,直接根据json⽣成(缺点:json数据全部展⽰,且只能按获取数据的顺序显⽰)//json数据转excelfunction JSONToExcelConvertor(JSONData, FileName) {//先转化jsonvar arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;var excel = '<table>';var row = "<tr>";//设置表头var keys = Object.keys(JSONData[0]);keys.forEach(function (item) {row += "<td>" + item + '</td>';});//换⾏excel += row + "</tr>";//设置数据for (var i = 0; i < arrData.length; i++) {var row = "<tr>";for (var index in arrData[i]) {console.log(arrData[i][index]);//var value = arrData[i][index] === "." ? "" : arrData[i][index];row += '<td>' + arrData[i][index] + '</td>';}excel += row + "</tr>";}excel += "</table>";var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='/TR/REC-html40'>"; excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';excelFile += '; charset=UTF-8">';excelFile += "<head>";excelFile += "<!--[if gte mso 9]>";excelFile += "<xml>";excelFile += "<x:ExcelWorkbook>";excelFile += "<x:ExcelWorksheets>";excelFile += "<x:ExcelWorksheet>";excelFile += "<x:Name>";excelFile += "{worksheet}";excelFile += "</x:Name>";excelFile += "<x:WorksheetOptions>";excelFile += "<x:DisplayGridlines/>";excelFile += "</x:WorksheetOptions>";excelFile += "</x:ExcelWorksheet>";excelFile += "</x:ExcelWorksheets>";excelFile += "</x:ExcelWorkbook>";excelFile += "</xml>";excelFile += "<![endif]-->";excelFile += "</head>";excelFile += "<body>";excelFile += excel;excelFile += "</body>";excelFile += "</html>";var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);var link = document.createElement("a");link.href = uri;link.style = "visibility:hidden";link.download = FileName + ".xls";document.body.appendChild(link);link.click();document.body.removeChild(link);}第⼆种json排序,可⼿动设置数据显⽰(缺点:⽆法对列间距进⾏设置,⽣成的excel会挤在⼀起)//导出访问路径Excelfunction exportPathMethod(data) {//要导出的json数据var jsonData = [];for(var i=0; i<data.length ; i++){jsonData.push({index :i+1,title: data[i].title,url: data[i].url,createTime :data[i].createTime});}//列标题,逗号隔开,每⼀个逗号就是隔开⼀个单元格let str = `序号,标题,地址,时间\n`;//增加\t为了不让表格显⽰科学计数法或者其他格式for(let i = 0 ; i < jsonData.length ; i++ ){for(let item in jsonData[i]){str+=`${jsonData[i][item] + '\t'},`;}str+='\n';}//encodeURIComponent解决中⽂乱码let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);//通过创建a标签实现var link = document.createElement("a");link.href = uri;//对下载的⽂件命名link.download = "json数据表.xls";document.body.appendChild(link);link.click();}<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"><script type="text/javascript" src="js/jquery-3.3.1.min.js"></script><script type="text/javascript" src="js/JSONToExcelConvertor.js"></script><script type="text/javascript">$(document).ready(function(){$('#wwo').click(function(){//测试的json数据var data3=[{"id":10000,"username":"user-0","sex":"⼥","city":"城市-0","sign":"签名-0","experience":255,"logins":24},{"id":10001,"username":"user-1","sex":"男","city":"城市-1","sign":"签名-1","experience":884,"logins":58} ,{"id":10002,"username":"user-2","sex":"⼥","city":"城市-2","sign":"签名-2","experience":650,"logins":77}]//⾃定义标题栏var title=['⽤户名','性别','城市','签名','经验']//⾃定义过滤栏(不需要导出的⾏)var filter=['id','logins']//原始导出JSONToExcelConvertor(data3,"report");//⾃定义导出//JSONToExcelConvertor(data3,"report",title,filter);});});</script></head><body><input type="button" id="wwo" value="导出"/></body></html>function JSONToExcelConvertor(JSONData, FileName,title,filter) {if(!JSONData)return;//转化json为objectvar arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;var excel = "<table>";//设置表头var row = "<tr>";if(title){//使⽤标题项for (var i in title) {row += "<th align='center'>" + title[i] + '</th>';}}else{//不使⽤标题项for (var i in arrData[0]) {row += "<th align='center'>" + i + '</th>';}}excel += row + "</tr>";//设置数据for (var i = 0; i < arrData.length; i++) {var row = "<tr>";for (var index in arrData[i]) {//判断是否有过滤⾏if(filter){if(filter.indexOf(index)==-1){var value = arrData[i][index] == null ? "" : arrData[i][index];row += '<td>' + value + '</td>';}}else{var value = arrData[i][index] == null ? "" : arrData[i][index];row += "<td align='center'>" + value + "</td>";}}excel += row + "</tr>";}excel += "</table>";var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='/TR/REC-html40'>"; excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';excelFile += '; charset=UTF-8">';excelFile += "<head>";excelFile += "<!--[if gte mso 9]>";excelFile += "<xml>";excelFile += "<x:ExcelWorkbook>";excelFile += "<x:ExcelWorksheets>";excelFile += "<x:ExcelWorksheet>";excelFile += "<x:Name>";excelFile += "{worksheet}";excelFile += "</x:Name>";excelFile += "<x:WorksheetOptions>";excelFile += "<x:DisplayGridlines/>";excelFile += "</x:WorksheetOptions>";excelFile += "</x:ExcelWorksheet>";excelFile += "</x:ExcelWorksheets>";excelFile += "</x:ExcelWorkbook>";excelFile += "</xml>";excelFile += "<![endif]-->";excelFile += "</head>";excelFile += "<body>";excelFile += excel;excelFile += "</body>";excelFile += "</html>";var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);var link = document.createElement("a");link.href = uri;link.style = "visibility:hidden";link.download = FileName + ".xls";document.body.appendChild(link);link.click();document.body.removeChild(link);}再次简化:终极简化导出excel(⼀万条数据可在10秒内导出)//json数据转excelfunction JSONToOrderExcelConvertor(JSONData) {var str = '序号,订单号,订单时间,主要⽤途,客户名称,电话,产品型号,是否形成有效线索\n';for(let i=0;i<JSONData.length;i++){var result ='';if (JSONData[i].orderStatusc=='0'){result="是";} else {result="否";}str += (i+1).toString()+','+JSONData[i].orderId+'\t'+','+formateOrderTime(JSONData[i].orderTime)+'\t'+','+JSONData[i].p1+'\t'+','+JSONData[i].userName+'\t'+','+JSONData[i].recMobile+'\t'+','+JSONData[i].productName+'\t'+','+result+'\t'+',\ }var blob = new Blob([str], {type: "text/plain;charset=utf-8"});//解决中⽂乱码问题blob = new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});object_url = window.URL.createObjectURL(blob);var link = document.createElement("a");link.href = object_url;link.download = "导出订单.xls";document.body.appendChild(link);link.click();document.body.removeChild(link);}第四种、使⽤插件导出js引⼊js<script src="https://cuikangjie.github.io/JsonExportExcel/dist/JsonExportExcel.min.js"></script>function JsonToExcel(jsonData,fileName,sheetName,sheetHeader) {var option = {};option.fileName = fileName;option.datas = [{sheetData : jsonData,sheetName : sheetName,sheetHeader : sheetHeader}];var toExcel=new ExportJsonExcel(option);toExcel.saveExcel();}由于使⽤nginx ,数据量超过俩万条时,请求时间超出nginx要求的响应时间就会报504 链接超时。
在JSP中实现查询并导入Excel的通用程序
模块。so . p hw j 模块负责连接数据库 、 s 执行 S L语 Q
句并将查询结 果 以二维数 组 的形 式 返 回, 示在 显 w b网页 上 。t lPit 数 负 责 创 建 Ecl 象 , e a er 函 b n xe 对 并从显示页面上读取数据写入 E cl 中。用户 可 xe 表 以在 Ecl xe表中进行保存 、 打印和统计分析的工作。 优点 : 利用 通 用查 询 程 序 开发 一 个 新 的查 询 模 块, 只要复制 主模块 , 更改查 询条件和 S L语句就 Q 可以了, 其他部分不用考 虑 , 5分钟就 能完成 , 减少 冗余重复的工作 , 降低了编程人员的工作量 ; 页面显
Ab t a t h sp p ri t d c s a meh d f rr aiig q i k s a c n mp rig EXC L g n rlp o rm ,as r s n sr c :T i a e r u e t o o e l n u c —e r h a d i o t n o z n E e e a rg a l pee t o t e p o r m o e l t n sp o e ta y a d d p n a l n p a t e h r g a c d i ,a d wa rv d se d n e e d be i r ci . s c
参数说明: bt 一 t t e 统计报表的名称 ; b 一网 ai l ri ad 页中 t l 的 i 名称 ; W一网页中 t l ae d b I O a e的行数 ;o b cl
霉
EaSL2 I m删 JI0 -iL 61 m: 6 IY _ G @c
维普资讯
格式设置和保存操作。整个过程只需一次连接数据
Jsp中Excel文件的导入
10.// });
11.
12.// 基本的读取
13.// 操作第一张表格
14.Sheet s = workBook.getSheet(0);
15.// 设置 row、cell
16.String[] row;
17.String cell;
18.// 循环输出表格内容
19.for (int i = s.getFirstRow(); i < s.getLastRow(); i++) {
System.out.print(cell.getContents()+" ");
}
System.out.println();
}
//利用已经创建的Excel工作薄创建新的可写入的Excel工作薄
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File("D://Book2.xls"),rwb);
26.}
27.// 关闭连接
workBook.close();
Java code
try { Class.forName("oracle.jdbc.OracleDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } String url="*****"; String user="*****"; String password="******"; try { conn = DriverManager.getConnection(url,user,password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { state = conn.createStatement(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } Workbook workbook = Workbook.getWorkbook(new File("C:/bjdmb.xls")); Sheet sheet = workbook.getSheet(0); int rows=sheet.getRows(); for(int i=1;i <rows;i++){ id="03"+sheet.getCell(1,i).getContents(); email=sheet.getCell(2,i).getContents(); sql="UPDATE id_accountdep SET reserved1='"+id+"' where depname= '"+email+"'"; state.executeUpdate(sql); System.out.println(sql); }
mvc-导出excel
MVC 导出EXCEL方法一:Jquery ajax post方式是无法直接导出excel的。
但可以先保存到服务器文件夹下,再从客户端下载1.前台页面JS部分://导出EXCELfunction Output() {var rowData = dg.datagrid('getData');var rowStr = JSON.stringify(rowData);$.ajax({type: "post",url: "/HeadquartersSet/OutPutExcel",data: { rowStr: rowStr },async: false,cache: false,success: function (text) {window.location.href = '/HeadquartersSet/DownloadFile/' + text;}});}2.control页面://生成EXCEL保存到服务器文件夹下,返回文件名public string OutPutExcel(){string rowStr = Request["rowStr"];int firstIndex = rowStr.IndexOf("[");string newStr = rowStr.Substring(firstIndex, rowStr.Length - firstIndex - 1);DataTable unitTable = (DataTable)Common.JSON.Decode(newStr,typeof(DataTable));//创建Excel文件的对象HSSFWorkbook book = new HSSFWorkbook();//添加一个sheetISheet sheet1 = book.CreateSheet("Sheet1");//貌似这里可以设置各种样式字体颜色背景等,但是不是很方便,这里就不设置了//给sheet1添加第一行的头部标题IRow row1 = sheet1.CreateRow(0);row1.CreateCell(0).SetCellValue("单位编码");row1.CreateCell(1).SetCellValue("单位名称");//....N行//将数据逐步写入sheet1各个行for (int i = 0; i < unitTable.Rows.Count; i++){IRow rowtemp = sheet1.CreateRow(i + 1);rowtemp.CreateCell(0).SetCellValue(unitTable.Rows[i]["UNIT_CODE"].ToString());rowtemp.CreateCell(1).SetCellValue(unitTable.Rows[i]["UNIT_NAME"].ToString());//....N行}//保存文件到服务器DateTime dt = DateTime.Now;string dateTime = dt.ToString("yyMMddHHmmssfff");string fileName = dateTime + ".xls";if (!Directory.Exists(Server.MapPath("/") + "SaveExcel"))//保存文件夹Directory.CreateDirectory(Server.MapPath("/") + "SaveExcel");string path = Server.MapPath("/") + "SaveExcel/" + dateTime + ".xls";while (System.IO.File.Exists(path))path = Server.MapPath("/") + "SaveExcel/" + dateTime + ".xls";FileStream file = new FileStream(path, FileMode.Create);//保存文件book.Write(file);file.Close();return fileName;}//下载EXCELpublic ActionResult DownloadFile(string id){string filePath = Server.MapPath("/") + "SaveExcel/" + id;System.IO.FileInfo file = new System.IO.FileInfo(filePath);if (file.Exists){Response.Clear();Response.AddHeader("Content-Disposition", "attachment; filename=" +);Response.AddHeader("Content-Length", file.Length.ToString());Response.ContentType = "application/octet-stream";Response.Filter.Close();Response.WriteFile(filePath);Response.Flush();Response.Close();if (System.IO.File.Exists(filePath))//删除服务器端文件System.IO.File.Delete(filePath);Response.End();}return new FileStreamResult(Response.OutputStream,"application/ms-excel/msword");}方法二:以form方式提交,可直接导出excel.如下:1.前台页面JS部分://导出EXCELfunction Output() {var rowData = dg.datagrid('getData');var rowStr = JSON.stringify(rowData);var $inputContent = $('<input>').attr({ name: "ResumeBody", value: rowStr });var $form = $("<form>");$form.attr({ target: '_self', method: 'post', action:'/HeadquartersSet/OutPutExcel' }).append($inputContent);$form.submit();}2. control页面:public FileResult OutPutExcel(FormCollection form){//string rowStr = Request["rowStr"];string rowStr = form[0];//ResumeBodyint firstIndex = rowStr.IndexOf("[");string newStr = rowStr.Substring(firstIndex, rowStr.Length - firstIndex - 1);DataTable unitTable = (DataTable)Common.JSON.Decode(newStr,typeof(DataTable));var sbHtml = new StringBuilder();sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");sbHtml.Append("<tr>");//var lstTitle = new List<string> { "编号", "姓名", "年龄", "创建时间" };var lstTitle = new List<string> { };for (int i = 0; i < unitTable.Columns.Count; i++){lstTitle.Add(unitTable.Columns[i].ColumnName);}foreach (var item in lstTitle){sbHtml.AppendFormat("<td style='font-size:14px;text-align:center;background-color: #DCE0E2; font-weight:bold;'height='25'>{0}</td>", item);}sbHtml.Append("</tr>");for (int i = 0; i < unitTable.Rows.Count; i++){sbHtml.Append("<tr>");for (int j = 0; j < unitTable.Columns.Count; j++){sbHtml.AppendFormat("<td style='font-size:12px;height:20px;'>{0}</td>", unitTable.Rows[i][j].ToString());}sbHtml.Append("</tr>");}sbHtml.Append("</table>");//使用FileContentResultbyte[] fileContents = Encoding.UTF8.GetBytes(sbHtml.ToString());return File(fileContents, "application/ms-excel", "fileContents.xls");}方法三(对方法二的优化):以form方式提交,可直接导出excel.如下:Html:添加<div id="page"></div>JS://导出$scope.outPut = function () {operationService.queryRecords($scope.page.searchModel).then(function (data) {if (data.HasError) {modal.dangerAlert(data.ErrorMessage);} else {var rowData = data.QueryResult;//拼Jason字符串//var rowStr = "[";//for (var i = 0; i < rowData.length; i++) {// rowStr += "{\"code\":\"" + rowData[i].code +"\",\"ticker\":\"" + rowData[i].ticker + "\",\"name\":\"" + rowData[i].name + "\",\"tradeDate\":\"" + rowData[i].tradeDate + "\",\"rate\":\"" + rowData[i].rate + "\",\"levelValue\":\"" + rowData[i].levelValue + "\",\"createDate\":\"" + rowData[i].createDate + "\",\"market\":\"" + rowData[i].market +"\",\"klineType\":\"" + rowData[i].klineType + "\"}";// if (i < rowData.length - 1) {// rowStr += ",";// }//}//rowStr += "]";var rowStr = JSON.stringify(rowData);/* google浏览器可用,火狐不可用var $inputContent = $('<input>').attr({ name: "ResumeBody", value: rowStr });var $form = $("<form>");$form.attr({target: '_self', method: 'post', action: '/Home/OutPutExcel' }).append($inputContent);$form.submit();*///兼容火狐浏览器和谷歌浏览器var pageDiv = document.getElementById("page");var temp = document.createElement("form");temp.action = "/Home/OutPutExcel";temp.method = "POST";temp.style.visibility = "hidden";var opt = document.createElement("input"); = "ResumeBody";opt.value = rowStr;temp.appendChild(opt); pageDiv.appendChild(temp);temp.submit();}});}control页面和方法二一样。
JS实现导出Excel的五种方法详解【附源码下载】
JS实现导出Excel的五种⽅法详解【附源码下载】本⽂实例讲述了JS实现导出Excel的五种⽅法。
分享给⼤家供⼤家参考,具体如下:这五种⽅法前四种⽅法只⽀持IE浏览器,最后⼀个⽅法⽀持当前主流的浏览器(⽕狐,IE,Chrome,Opera,Safari)<!DOCTYPE html><html><head lang="en"><meta charset="UTF-8"><title>html 表格导出道</title><script language="JavaScript" type="text/javascript">//第⼀种⽅法function method1(tableid) {var curTbl = 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(curTbl);sel.select();sel.execCommand("Copy");oSheet.Paste();oXL.Visible = true;}//第⼆种⽅法function method2(tableid){var curTbl = document.getElementById(tableid);var oXL = new ActiveXObject("Excel.Application");var oWB = oXL.Workbooks.Add();var oSheet = oWB.ActiveSheet;var Lenr = curTbl.rows.length;for (i = 0; i < Lenr; i++){ var Lenc = curTbl.rows(i).cells.length;for (j = 0; j < Lenc; j++){oSheet.Cells(i + 1, j + 1).value = curTbl.rows(i).cells(j).innerText;}}oXL.Visible = true;}//第三种⽅法function getXlsFromTbl(inTblId, inWindow){try {var allStr = "";var curStr = "";if (inTblId != null && inTblId != "" && inTblId != "null") {curStr = getTblData(inTblId, inWindow);}if (curStr != null) {allStr += curStr;}else {alert("你要导出的表不存在");return;}var fileName = getExcelFileName();doFileExport(fileName, allStr);}catch(e) {alert("导出发⽣异常:" + + "->" + e.description + "!");}}function getTblData(inTbl, inWindow) {var rows = 0;var tblDocument = document;if (!!inWindow && inWindow != "") {if (!document.all(inWindow)) {return null;}else {tblDocument = eval(inWindow).document;}}var curTbl = tblDocument.getElementById(inTbl);var outStr = "";if (curTbl != null) {for (var j = 0; j < curTbl.rows.length; j++) {for (var i = 0; i < curTbl.rows[j].cells.length; i++) {if (i == 0 && rows > 0) {outStr += " t";rows -= 1;}outStr += curTbl.rows[j].cells[i].innerText + "t";if (curTbl.rows[j].cells[i].colSpan > 1) {for (var k = 0; k < curTbl.rows[j].cells[i].colSpan - 1; k++) {outStr += " t";}}if (i == 0) {if (rows == 0 && curTbl.rows[j].cells[i].rowSpan > 1) {rows = curTbl.rows[j].cells[i].rowSpan - 1;}}}outStr += "rn";}}else {outStr = null;alert(inTbl + "不存在 !");}return outStr;}function getExcelFileName() {var d = new Date();var curYear = d.getYear();var curMonth = "" + (d.getMonth() + 1);var curDate = "" + d.getDate();var curHour = "" + d.getHours();var curMinute = "" + d.getMinutes();var curSecond = "" + d.getSeconds();if (curMonth.length == 1) {curMonth = "0" + curMonth;}if (curDate.length == 1) {curDate = "0" + curDate;}if (curHour.length == 1) {curHour = "0" + curHour;}if (curMinute.length == 1) {curMinute = "0" + curMinute;}if (curSecond.length == 1) {curSecond = "0" + curSecond;}var fileName = "table" + "_" + curYear + curMonth + curDate + "_"+ curHour + curMinute + curSecond + ".csv";return fileName;}function doFileExport(inName, inStr) {var xlsWin = null;if (!!document.all("glbHideFrm")) {xlsWin = glbHideFrm;}else {var width = 6;var height = 4;var openPara = "left=" + (window.screen.width / 2 - width / 2)+ ",top=" + (window.screen.height / 2 - height / 2)+ ",scrollbars=no,width=" + width + ",height=" + height;xlsWin = window.open("", "_blank", openPara);}xlsWin.document.write(inStr);xlsWin.document.close();xlsWin.document.execCommand('Saveas', true, inName);xlsWin.close();}//第四种function method4(tableid){var curTbl = document.getElementById(tableid);var oXL;try{oXL = new ActiveXObject("Excel.Application"); //创建AX对象excel}catch(e){alert("⽆法启动Excel!\n\n如果您确信您的电脑中已经安装了Excel,"+"那么请调整IE的安全级别。
网页数据导出excel的方法
如何抓取和导出网页数据,并保存到本地?如何才能将网页数据(文字,图片等)等导出,保存到本地,以方便在想看的时候就看或者后续更深层次的数据处理?导出网页数据一般有如下几种方法。
一、通过浏览器导出网页数据具体操作:打开某网页后,右键点击网页空白处,在下拉列表中选择“另存为”,然后在弹出的保存窗口中选择保存类型为“网页全部”。
选择保存位置后确定,保存后就会自动保存两个文件,一个是网址,另一个是保存网页内容元素。
如何导出网页数据,以赶集网采集为例图1二、通过网页数据采集器导出网页数据先通过网页数据采集器,将网页数据采集下来,然后再导出为需要的格式即可。
本文使用的是操作简单、功能强大的八爪鱼采集器。
以下是一个八爪鱼采集并导出网页数据的完整示例。
示例中采集的是赶集网上房产-商铺-深圳-南山分类下的所有商铺信息。
示例网站:/fang6/nanshan/步骤1:创建采集任务1)进入主界面,选择“自定义模式”如何导出网页数据,以赶集网采集为例图22)将要采集的网址URL,复制粘贴到网址输入框中,点击“保存网址”如何导出网页数据,以赶集网采集为例图3步骤2:创建翻页循环1)在页面右上角,打开“流程”,以展现出“流程设计器”和“定制当前操作”两个板块。
将页面下拉到底部,点击“下一页”按钮,在右侧的操作提示框中,选择“循环点击下一页”如何导出网页数据,以赶集网采集为例图4步骤3:创建列表循环1)移动鼠标,选中页面里的第一个商铺链接。
选中后,系统会自动识别页面里的其他相似链接。
在右侧操作提示框中,选择“选中全部”如何导出网页数据,以赶集网采集为例图52)选择“循环点击每个链接”,以创建一个列表循环如何导出网页数据,以赶集网采集为例图6步骤4:提取商铺信息1)在创建列表循环后,系统会自动点击第一个商铺链接,进入商铺详细信息页。
点击需要的字段信息,在右侧的操作提示框中,选择“采集该元素的文本”如何导出网页数据,以赶集网采集为例图72)字段信息选择完成后,选中相应的字段,可以进行字段的自定义命名。
使用js-xlsx导出表格
使⽤js-xlsx导出表格⾸先导⼊ xlsx.full.min.js建⽴表格数据下⾯是关键代码<a download="表格导出excel" id="excelOut" href="#" class="btn_a">导出</a>//base64转码var base64 = function (s) {return window.btoa(unescape(encodeURIComponent(s)));};//替换table数据和worksheet名字var format = function (s, c) {return s.replace(/{(\w+)}/g,function (m, p) {return c[p];});}function tableToExcel(tableid, sheetName) {var uri = 'data:application/vnd.ms-excel;base64,';var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"' + 'xmlns="/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>'+ '<x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet> </x:ExcelWorksheets>'+ '</x:ExcelWorkbook></xml><![endif]-->' +' <style type="text/css">' +'table td {' +'border: 1px solid #000000;' +'width: 100px;' +'height: 30px;' +' text-align: center;' +' }' +'</style>' +'</head><body ><table class="excelTable">{table}</table></body></html>';if (!tableid.nodeType) tableid = document.getElementById("materials_table");var ctx = {worksheet: sheetName || 'Worksheet', table: tableid.innerHTML};document.getElementById("excelOut").href = uri + base64(format(template, ctx));}。
前端vue使用js-xlsx导出excel的三种方法
前端vue使⽤js-xlsx导出excel的三种⽅法npm install --save xlsx file-saver在组件⾥⾯引⼊import FileSaver from'file-saver'import XLSX from'xlsx'第⼀种其中#outTable是在el-table上定义的idexportExcel() {var xlsxParam = { raw: true };//转换成excel时,使⽤原始的格式var wb = XLSX.utils.table_to_book(document.querySelector("#outTable"),xlsxParam);//outTable为列表idvar wbout = XLSX.write(wb, {bookType: "xlsx",bookSST: true,type: "array"});try {FileSaver.saveAs(new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),"sheetjs.xlsx");} catch (e) {if (typeof console !== "undefined") console.log(e, wbout);}return wbout;}第⼆种通过数组导出excelvar _data = [[ "id", "name", "value" ],[ 1, "sheetjs", 7262 ],[ 2, "js-xlsx", 6969 ]];const ws= XLSX.utils.aoa_to_sheet(_data);/* generate workbook and add the worksheet */const wb = XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');/* save to file */XLSX.writeFile(wb, 'SheetJS.xlsx');第三种通过json导出excelexportExcel() {var wopts = {bookType: 'xlsx',bookSST: true,type: 'binary'};var workBook = {SheetNames: ['Sheet1'],Sheets: {},Props: {}};var table = [];for(var i=0;i<this.multipleSelection.length;i++){var params = {姓名: this.multipleSelection[i].name,部门: this.multipleSelection[i].department,职务名称: this.multipleSelection[i].titles,档案编号:this.multipleSelection[i].fileNum,校验状态:this.multipleSelection[i].verifyStatus,审核状态:this.multipleSelection[i].checkedStatus,备注:this.multipleSelection[i].checkedReason,}table[i] = params};//1、XLSX.utils.json_to_sheet(data) 接收⼀个对象数组并返回⼀个基于对象关键字⾃动⽣成的“标题”的⼯作表,默认的列顺序由使⽤Object.keys的字段的第⼀次出现确定 //2、将数据放⼊对象workBook的Sheets中等待输出workBook.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(table);//3、XLSX.write() 开始编写Excel表格//4、changeData() 将数据处理成需要输出的格式FileSaver.saveAs(new Blob([this.changeData(XLSX.write(workBook, wopts))], {type: 'application/octet-stream'}), "sheetjs.xlsx")},changeData(s) {//如果存在ArrayBuffer对象(es6) 最好采⽤该对象if (typeof ArrayBuffer !== 'undefined') {//1、创建⼀个字节长度为s.length的内存区域var buf = new ArrayBuffer(s.length);//2、创建⼀个指向buf的Unit8视图,开始于字节0,直到缓冲区的末尾var view = new Uint8Array(buf);//3、返回指定位置的字符的Unicode编码for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;return buf;} else {var buf = new Array(s.length);for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;return buf;}},第三种适合导出选中的数据如果选中的json数据字段都是你需要的可以⽤下⾯的⽅法导出const workSheet =XLSX.utils.json_to_sheet(this.multipleSelection, {header: ['列1', '列2', '列3', '列1', '列2', '列3', '列1', '列2'],skipHeader: true// 跳过上⾯的标题⾏});const ws = XLSX.utils.aoa_to_sheet(workSheet);const wb = XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');/* save to file */XLSX.writeFile(wb, 'SheetJS.xlsx');。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
jsp页面内容导出到Excel中
日常使用网络资源时经常需要把网页中的内容下载到本地,并且导出到Excel中,现在介绍一种非常简单的方式实现网络资源的下载。
只需要讲jsp的最上面加上一句话
<%
response.reset();
response.setContentType("application/vnd.ms-excel;charset=GBK");
%>
就可以将网页的内容导出为Excel。
目前给出的例子为了方便起见,就是使用了纯粹的静态页面,一个table其中有一行是标题,一行是内容,但是实际使用中不可能这么简单,都是保持静态的内容,如果需要保存的内容是从数据库中取出,则只需要循环遍历取出的内容,添加行就行了,假如从数据库中取出的数据存入UserList 中,可以使用struts标签进行遍历如下:
<table class="common1"cellpadding="5"cellspacing="1"align="center"> <tr>
<td class=formtitle colspan="4"><CENTER>清单</CENTER></td>
</tr>
<tr>
<td class=formtitle align="center"nowrap style="width:13%">姓名
</td>
<td class=formtitle align="center"nowrap style="width:13%">年龄
</td>
<td class=formtitle align="center"nowrap style="width:13%">性别
</td>
<td class=formtitle align="center"nowrap style="width:13%">住址
</td>
</tr>
<logic:present name="UserList">
<logic:iterate id="user"name="UserList">
<tr>
<td align="center"nowrap style="width:13%">
<bean:write name = "user",property="name"/>
</td>
<td align="center"nowrap style="width:13%">
<bean:write name = "user",property="age"/>
</td>
<td align="center"nowrap style="width:13%">
<bean:write name = "user",property="sex"/>
</td>
<td align="center"nowrap style="width:13%">
<bean:write name = "user",property="address"/>
</td>
</tr>
</logic:iterate>
</logic:present>
</table>
下面是完整的例子,新建Dynamic Web Project,在WebContent下新建一个index.jsp,里面只需要一个超链接<a href = 'DownLoadExcel.jsp'>导出Excel</a>
再新建一个DownLoadExcel.jsp,内容如下:
<%
response.reset();
response.setContentType("application/vnd.ms-excel;charset=GBK");
%>
<html>
<head>
<title>刷卡消费情况</title>
<style type="text/css">
mon1 { width: 100%;
font-size: 9pt;
style-align: center;
background-color: #ffffff;
}
td.formtitle { font-size: 9pt;
background:#a480b2;
color:#ffffff;
height:30px;
text-align: center;}
</style>
</head>
<body>
<form name="fm"method="post">
<table class="common1"cellpadding="5"cellspacing="1"align="center" >
<tr>
<td class=formtitle colspan="4"><CENTER>清单</CENTER></td> </tr>
<tr>
<td class=formtitle align="center"nowrap style="width:13%">姓名</td>
<td class=formtitle align="center"nowrap style="width:13%">年龄</td>
<td class=formtitle align="center"nowrap style="width:13%">性别</td>
<td class=formtitle align="center"nowrap style="width:13%">家庭住址</td>
</tr>
<tr>
<td align="center"nowrap style="width:13%">张三</td>
<td align="center"nowrap style="width:13%">25</td>
<td align="center"nowrap style="width:13%">男</td>
<td align="center"nowrap style="width:13%">北京中关村</td> </tr>
</table>
</form>
</body>
</html>
部署好程序,在index.jsp中点击超链接就可以完成导出了。