JSP中导入导出Excel文件
- 格式:doc
- 大小:123.00 KB
- 文档页数:36
前端sheetjs导出excel设置百分⽐格式概述前端导出 excel ⽂件常⽤的库是。
今天 PM 提了⼀个需求就是所有的数字都使⽤数字格式,特别是百分⽐也使⽤数字格式。
我想了很久终于解决了,记录下来,供以后开发时参考,相信对其它⼈也有⽤。
问题通过查看,我们可以发现,它⽀持这⼏种导出格式:Boolean、Error、Number、Date、Text、Stub,⾥⾯没有百分⽐格式,怎么办呢?⽅法就是使⽤格式化为 0.00% 的数字格式,其中后⾯2个0是⾃定义2个⼩数位,可以多加或者少加。
源码Show me the code:const workbook = XLSX.utils.book_new();const sheet = XLSX.utils.json_to_sheet(data);Object.keys(sheet).forEach((item) => {const cell = sheet[item];const value = cell.v;if (cell.t === 's' && value.indexOf('%') > -1) {cell.z = '0.00%';cell.t = 'n';cell.v = Number(value.substring(0, value.length - 1)) / 100;}});XLSX.utils.book_append_sheet(workbook, sheet, 'Sheet1');XLSX.writeFile(workbook, filename);题外话这个库真的很强⼤,还可以⾃定义很多其他的东西。
安利⼀下我⾃⼰写的 excel 导出库。
环境配置1 正确安装配置java的jdk2 将ireport放到c:\ireport3 将ant放到c:\ant(我用的是bea的ant路径是D:\bea\weblogic81\server\ant)4 将jasperreports-1.2.0.jar 放置到当前classpath中(没有加,我使用的Ireport\lib下已经存在了)5 将itext-1.3.1.jar放置到c:\ireport\lib(没有加,我使用的Ireport\lib下已经存在了)6 修改ireport\ireport.bat文件,加入以下内容set JAVA_HOME=C:\j2sdk1.4.2set ANT_HOME=D:\bea\weblogic81\server\set IREPORT_HOME=c:\ireport rem %ANT_HOME%\bin\ant javadocs %ANT_HO ME%\bin\ant iReport我修改的是:set JAVA_HOME=C:\j2sdk1.4.2set ANT_HOME=D:\bea\weblogic81\server\set IREPORT_HOME=F:\backup\iReport-1.2.0 rem %ANT_HOME%\bin\ant javadocs %ANT_HOME%\bin\ant iReport(不过对以上修改,感觉没有什么用处)7 提供一个正常提供服务的数据库现在高版本的ireport是不需要进行配置,可以直接使用的.了解制作报表用的包1 jasperreports-1.0.1.jar jasperreports是iReport的核心内容,jsperreport是一个报表制作程序,用它的规则制定一个xml文件,然后编译生成一个.jsper文件,这个.jsper文件是我们真正使用的,它很象.jsp文件,使用的是它编译后的servlet. (http://jasperreports.sou /)2 itext-1.3.1.jar iText是一个开放源码的Java类库,是用来生成PDF文件的。
js导⼊导出excel(实例代码)复制代码代码如下:<html xmlns="/1999/xhtml" ><head><title>Untitled Page</title></head><script language="javascript" type="text/javascript">function importXLS(fileName){objCon = new ActiveXObject("ADODB.Connection");objCon.Provider = "Microsoft.Jet.OLEDB.4.0";objCon.ConnectionString = "Data Source=" + fileName + ";Extended Properties=Excel 8.0;";objCon.CursorLocation = 1;objCon.Open;var strQuery;//Get the SheetNamevar strSheetName = "Sheet1$";var rsTemp = new ActiveXObject("ADODB.Recordset");rsTemp = objCon.OpenSchema(20);if(!rsTemp.EOF)strSheetName = rsTemp.Fields("Table_Name").Value;rsTemp = null;rsExcel = new ActiveXObject("ADODB.Recordset");strQuery = "SELECT * FROM [" + strSheetName + "]";rsExcel.ActiveConnection = objCon;rsExcel.Open(strQuery);while(!rsExcel.EOF){for(i = 0;i<rsExcel.Fields.Count;++i){alert(rsExcel.Fields(i).value);}rsExcel.MoveNext;}// Close the connection and dispose the fileobjCon.Close;objCon =null;rsExcel = null;}</script></head><body><input type="file" id="f" /><input type="button" id="b" value="import" onclick="if(f.value=='')alert('请选择xls⽂件');else importXLS(f.value)" /> </body></html>复制代码代码如下:function AutomateExcel(){// 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 = "First Name";oSheet.Cells(1, 2).Value = "Last Name";oSheet.Cells(1, 3).Value = "Full Name";oSheet.Cells(1, 4).Value = "Salary";// Format A1:D1 as bold, vertical alignment = center.oSheet.Range("A1", "D1").Font.Bold = true;oSheet.Range("A1", "D1").VerticalAlignment = -4108; //xlVAlignCenter// Create an array to set multiple values at once.// Fill A2:B6 with an array of values (from VBScript).oSheet.Range("A2", "B6").Value = CreateNamesArray();// Fill C2:C6 with a relative formula (=A2 & " " & B2).var oRng = oSheet.Range("C2", "C6");oRng.Formula = "=A2 & " " & B2";// Fill D2:D6 with a formula(=RAND()*100000) and apply format.oRng = oSheet.Range("D2", "D6");oRng.Formula = "=RAND()*100000";oRng.NumberFormat = "$0.00";// AutoFit columns A:D.oRng = oSheet.Range("A1", "D1");oRng.EntireColumn.AutoFit();// Manipulate a variable number of columns for Quarterly Sales Data. DispalyQuarterlySales(oSheet);// Make sure Excel is visible and give the user control// of Excel's lifetime.oXL.Visible = true;erControl = true;}<HTML><HEAD><TITLE>将页⾯中指定表格的数据导⼊到Excel中</TITLE><SCRIPT LANGUAGE="javascript"><!--function AutomateExcel(){var oXL = new ActiveXObject("Excel.Application"); //创建应该对象var oWB = oXL.Workbooks.Add();//新建⼀个Excel⼯作簿var oSheet = oWB.ActiveSheet;//指定要写⼊内容的⼯作表为活动⼯作表var table = document.all.data;//指定要写⼊的数据源的idvar hang = table.rows.length;//取数据源⾏数var lie = table.rows(0).cells.length;//取数据源列数// Add table headers going cell by cell.for (i=0;i<hang;i++){//在Excel中写⾏for (j=0;j<lie;j++){//在Excel中写列//定义格式oSheet.Cells(i+1,j+1).NumberFormatLocal = "@";//上⾯这⼀句是将单元格的格式定义为⽂本oSheet.Cells(i+1,j+1).Font.Bold = true;//加粗oSheet.Cells(i+1,j+1).Font.Size = 10;//字体⼤⼩oSheet.Cells(i+1,j+1).value = table.rows(i).cells(j).innerText;//向单元格写⼊值}}oXL.Visible = true;erControl = true;}//--></SCRIPT></HEAD><BODY><table border="0" width="300" id="data" bgcolor="black" cellspacing="1"><tr bgcolor="white"><td>编号</td><td>姓名</td><td>年龄</td><td>性别</td></tr><tr bgcolor="white"><td>0001</td><td>张三</td><td>22</td><td>⼥</td></tr><tr bgcolor="white"><td>0002</td><td>李四</td><td>23</td><td>男</td></tr></table><input type="button" name="out_excel" onclick="AutomateExcel();" value="导出到excel"></BODY></HTML>复制代码代码如下:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd"><!-- 导出excle的三个⽅法要把ie浏览器的"对没有标记为安全的 ActiveX 控件进⾏初始化和脚本运⾏设置为提⽰或启⽤" --> <html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>WEB页⾯导出为EXCEL⽂档的⽅法</title></head><body><table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0"><tr><td colspan="5" align="center">WEB页⾯导出为EXCEL⽂档的⽅法</td></tr><tr><td>列标题1</td><td>列标题2</td><td>列标题3</td><td>列标题4</td><td>列标题5</td></tr><tr><td>aaa</td><td></td><td>ccc</td><td>ddd</td><td>eee</td></tr><tr><td>AAA</td><td></td><td>CCC</td><td>DDD</td><td>EEE</td></tr><tr><td>FFF</td><td>GGG</td><td>HHH</td><td>III</td><td>JJJ</td></tr></table><input type="button" onclick="javascript:method1('tableExcel');" value="第⼀种⽅法导⼊到EXCEL"><input type="button" onclick="javascript:method2('tableExcel');" value="第⼆种⽅法导⼊到EXCEL"><input type="button" onclick="javascript:getXlsFromTbl('tableExcel',null);" value="第三种⽅法导⼊到EXCEL"> <script language="javascript">function method1(tableid) {//整个表格拷贝到EXCEL中var curTbl = document.getElementById(tableid);var oXL = new ActiveXObject("Excel.Application"); //创建AX对象excelvar oWB = oXL.Workbooks.Add(); //获取workbook对象var oSheet = oWB.ActiveSheet; //激活当前sheetvar sel = document.body.createTextRange();sel.moveToElementText(curTbl); //把表格中的内容移到TextRange中sel.select(); //全选TextRange中内容sel.execCommand("Copy"); //复制TextRange中内容oSheet.Paste(); //粘贴到活动的EXCEL中oXL.Visible = true; //设置excel可见属性}function method2(tableid) //读取表格中每个单元到EXCEL中{var curTbl = document.getElementById(tableid);var oXL = new ActiveXObject("Excel.Application"); //创建AX对象excelvar oWB = oXL.Workbooks.Add(); //获取workbook对象var oSheet = oWB.ActiveSheet; //激活当前sheetvar 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; //设置excel可见属性}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 += "/r/n";}}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 = "leo_zhang" + "_" + 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();}</script></body></html>。
JS操作EXCEL大全JavaScript 是一种非常流行的编程语言,广泛用于 Web 开发。
虽然JavaScript 不是用来处理 Excel 文件的首选语言,但我们仍然可以使用一些第三方库和 JavaScript 内置的功能来操作 Excel 文件。
在接下来的文章中,我们将介绍一些常见的技术和库,以便在 JavaScript 中操作Excel 文件。
1. 使用 JavaScript 原生 API 操作 Excel 文件:JavaScript 提供了一些用于处理文件的 API,可以使用这些 API 执行一些基本的 Excel 文件操作。
例如,可以使用 FileReader API 读取Excel 文件,然后使用 JavaScript 操作数据。
这种方式主要适用于读取较小的 Excel 文件。
2.使用第三方库:2.1. ExcelJS:ExcelJS 是一个流行的 JavaScript 库,用于在浏览器和 Node.js 中操作 Excel 文件。
它提供了许多用于读取、写入和修改Excel 文件的方法。
您可以使用 ExcelJS 创建、读取和修改 Excel 文件,并进行复杂的数据操作,例如合并单元格、设置单元格样式等。
2.2. xlsx-populate:xlsx-populate 是另一个用于操作 Excel 文件的库,它提供了丰富的 API,使开发人员能够在浏览器和 Node.js 中读取和写入 Excel 文件。
它支持各种 Excel 功能,如图表、公式、数据验证等。
2.3. Excel4Node:Excel4Node 是一个用于操作 Excel 文件的轻量级库。
它使用 Apache POI 库来处理 Excel 文件,并提供了一组简单而强大的 API。
你可以使用 Excel4Node 通过浏览器或 Node.js 读取、写入和修改 Excel 文件。
3. 数据导出为 Excel 格式:你可以使用 JavaScript 将数据导出为 Excel 格式。
js导出excel⽂件的简洁⽅法(推荐)⽤js可以直接在jsp页⾯导出数据到excel⽂件,⽅法很简洁,如下:第⼀,准备⼀个jsp(暂时取名为export.jsp),内容为:<%@ page contentType="text/html; charset=GBK"%><%String context = request.getParameter("sContent");response.setHeader("Content-type","application/vnd.ms-xls");response.setHeader("Content-Disposition","attachment;filename=export.xls");response.setHeader("Expires","0");response.setHeader("Cache-Control", "no-cache, must-revalidate");response.setHeader("Pragma", "no-cache");out.print(context);%>第⼆,写⼀个导出数据的jsp页⾯(暂时命名为test.jsp),内容如下:<%@ page contentType="text/html; charset=GBK"%><%String path = request.getContextPath();%><html><head><script type="text/javascript">function exportData(){var html="<table><tr><td>星期⼀</td><td>星期⼆</td><td>星期三</td><td>星期四</td></tr>";html+="<tr><td>monday</td><td>tuesday</td><td>wednesday</td><td>thursday</td>";html+="</tr></table>";document.getElementByIdx_x_x("sContent").value=html;document.getElementByIdx_x_x("form1").submit();}</script></head><body><iframe id="exeframe" name="exeframe" style="display:none"></iframe><form id="form1" method="post" target="exeframe" action="export.jsp?ver=导出"><input type="hidden" id="sContent" name="sContent" value=""/></form><input type="button" onclick="exportData()" value="导出"></body></html>ok,⾄此,导出功能结束。
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页面中导出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的三种可行方法[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>。
Web导出excel的几种方法Web导出excel的几种方法ExcelWebIE浏览器应用服务器在项目中我们经常遇到需要将报表导出成excel下载保存下来,在不同的要求和不同的资源情况下我们有不同的处理方式。
在这里我将谈谈我所遇到的几种情况和遇到的一些问题。
总的来说可以分为:服务器端生成和浏览器端生成2种方法。
一、服务器端生成就是:根据用户请求,获取相应的数据,使用poi/jxl, jacob/jawin+excel或是用数据拼html的table或是cvs纯文本的数据格式等。
然后按.xls或是.cvs格式的文件的形式返回给用户,指定Content-Type:application/vnd.ms-excel ,浏览器就会提示要下载的文件是excel文件。
一般情况下采用这种方式的话就可以根据具体要求对excel文件进行细致的处理,各方面样式和排列可以自己控制使用,而且是可以跨平台使用的。
缺点就是毕竟需要根据不同的表格进行不断的coding,服务器也有一定的压力,这里我就不进行例子解释了。
二、浏览器端生成excel文件还没有特别完善的方案,这是因为js 无法处理二进制。
大概有以下几个方案,各有利弊1.activex方式:使用js调用excel对象,传入需要的参数直接导出excel。
这种方式代码简单,速度较快,前段时间用过2种采用这种方式的方法,各有千秋:A:页面table拷贝法:var curTbl = document.getElementById(tableid);var oXL = new ActiveXObject("Excel.Application");var oWB = oXL.Workbooks.Add(); //创建AX对象excelvar oSheet = oWB.ActiveSheet; //获取workbook对象var sel = document.body.createTextRange(); //激活当前sel.moveToElementText(curTbl); //把表格中的内容移到TextRange中sel.select(); //全选TextRange中内容sel.execCommand("Copy"); //复制TextRange中内容oSheet.Paste(); //粘贴到活动的EXCEL中oXL.Visible = true; //设置excel可见属性如上代码可见,这个方法需要传入的就是table的ID,通过拷贝table复制到excel的方式执行,这个方法的特点是可见即所得,当然页面格子大小不能控制精细,只能得到当前页面展示的table部分,如table做了分页处理的话,直接导出的也只是当前页面部分。
SpreadJS在V10版本后推出了纯前端的Excel导入导出,这个功能可以很方便的实现客户端的Excel导入导出,但是如果用户需要导入导出到浏览器端又该怎么办呢?其实纯前端的Excel导入导出同样可以实现服务器端的Excel导入导出。
下面让我们来看一下是如何实现的:本示例的后端使用JAVA语言,通过SpreadJS的前端导出导出与JAVA后端结合,实现分从服务器端导入Excel与导出Excel保存至服务器端这两个功能:从服务器端导入Excel:这部分使用纯前端实现,纯前端实现有一个弊端就是,浏览器没有权限访问服务器上工程目录以外的路径,所以需要将服务器端的Excel放入工程目录下。
然后下载到前端直接打开,核心代码如下:var excelIo = new GC.Spread.Excel.IO();var excelFilePath = 'resources/Excel/importExcel.xlsx';var xhr = new XMLHttpRequest();xhr.open('GET', excelFilePath, true);xhr.responseType = 'blob';xhr.onload = function(e) {if(this.status == 200) {// get binary data as a responsevar blob = this.response;// convert Excel to JSONexcelIo.open(blob, function(json) {var workbookObj = json;spread.fromJSON(workbookObj);}, function(e) {// process erroralert(e.errorMessage);}, {});}};xhr.send();导出Excel保存至服务器端:这部分使用前端导出功能与后端java结合的方式来实现,首先通过前端Excel导出,生成导出文件,然后通过formdata来承载导出文件,之后通过ajax将formdata传至后端java。
JS操作EXCEL大全一、读取Excel文件读取Excel文件是进行Excel操作的基础。
在JavaScript中,我们可以使用一些库来读取Excel文件,例如xlsx、xlsjs和exceljs等。
1. 使用xlsx库读取Excel文件xlsx是一个用于处理Excel文件的JavaScript库。
您可以通过以下步骤使用xlsx库来读取Excel文件:首先,将xlsx库导入到您的项目中。
您可以使用npm来安装xlsx库,并在代码中引入该库:```npm install xlsxconst XLSX = require('xlsx');```然后,使用XLSX.readFile方法读取Excel文件:```const workbook = XLSX.readFile('example.xlsx');```最后,可以通过workbook.Sheets对象获取Excel文件的内容:```const worksheet = workbook.Sheets['Sheet1'];console.log(XLSX.utils.sheet_to_json(worksheet));```2. 使用xlsjs库读取Excel文件xlsjs是另一个用于读取Excel文件的JavaScript库。
您可以使用以下步骤使用xlsjs库来读取Excel文件:首先,将xlsjs库导入到您的项目中。
您可以使用npm来安装xlsjs 库,并在代码中引入该库:```npm install xlsjsconst XLSX = require('xlsjs');```然后,使用XLSX.readFile方法读取Excel文件:```const workbook = XLSX.readFile('example.xls');```最后,可以通过workbook.Sheets对象获取Excel文件的内容:```const worksheet = workbook.Sheets['Sheet1'];console.log(XLSX.utils.sheet_to_json(worksheet));```二、写入Excel文件在读取Excel文件之后,我们还可以使用JavaScript来写入Excel 文件。
下面代码有选择的粘贴进自己项目即可,其实现解决了tomcat、resin服务器中文下载乱码问题。
web.xml配置如下<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_2_5.xsd"><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><filter><filter-name>downLoad</filter-name><filter-class>com.tangdi.DownLoadFilter</filter-class></filter><filter-mapping><filter-name>downLoad</filter-name><url-pattern>*.downLoad</url-pattern></filter-mapping></web-app>Jsp页面配置如下其下载利用a标签进行连接,前提是服务器上下载文件路径已知需要引进el表达式和jquery.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib uri="/jsp/jstl/core" prefix="c"%><script src="${pageContext.request.contextPath}/js/jquery-1.4.4.min.js" type="text/javascript"></script><html><head><script>$(function(){var$href='${pageContext.request.contextPath}'+"/20159.downLoad?filePath=";//+encodeURICompo nent("中国.downLoad");$("#testHref").children("td").each(function(){var $id=$(this).children(":first").attr("id");var $tmpHref="";if($id=="txt"){$tmpHref=$href+"E:/apache-tomcat-6.0.35/apache-tomcat-6.0.35/webapps/MyTry/test/"+"203123 4_这是txt.txt";}else if($id=="pdf"){$tmpHref=$href+"E:/apache-tomcat-6.0.35/apache-tomcat-6.0.35/webapps/MyTry/test/"+"这是pdf.pdf";}else if($id=="excel"){$tmpHref=$href+"这是excel.xls";}else if($id=="word"){$tmpHref=encodeURI($href+"这是doc.doc","ISO8859-1");}else if($id=="jpg"){$tmpHref=$href+"这是jpg.jpg";}else if($id=="js"){$tmpHref=$href+"这是js.js";}else if($id=="jsp"){$tmpHref=$href+"这是jsp.jsp";}else if($id=="html"){$tmpHref=$href+"这是html.html";}$(this).children(":first").attr("href",$tmpHref);});});</script></head><body><div><table><tr id="testHref"><td><a id="txt" href="#">txt</a></td><td><a id="pdf" href="#">pdf</a></td><td><a id="excel" href="#">excel</a></td><td><a id="word" href="#">word</a></td><td><a id="xml" href="#">xml</a></td><td><a id="jpg" href="#">jpg</a></td><td><a id="gif" href="#">gif</a></td><td><a id="js" href="#">js</a></td><td><a id="jsp" href="#">jsp</a></td><td><a id="html" href="#">html</a></td></tr></table></div></body></html>过滤器filter配置如下package com.tangdi;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import .URLDecoder;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class DownLoadFilter implements Filter {public void destroy() {}public void doFilter(ServletRequest request1, ServletResponse response1,FilterChain arg2) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) request1;HttpServletResponse response = (HttpServletResponse) response1;//request.setCharacterEncoding("UTF-8");//String filePath = new String(request.getParameter("filePath").getBytes("ISO8859-1"), "UTF-8");request.setCharacterEncoding("ISO8859-1");String filePath = new String(request.getParameter("filePath").getBytes("ISO8859-1"),"UTF-8");System.out.println("*****************************************************filePat h is :" + filePath);String suffix = filePath.substring(stIndexOf(".") + 1);System.out.println("********************suffix is:"+suffix);String contentType = getContentType(suffix);//获得尾缀设置不同contentTypeString contentDisposition = "attachment; filename="+new String(filePath.substring(stIndexOf("_")+1));System.out.println("********************************************"+contentDisposit ion);response.setCharacterEncoding("ISO8859-1");response.setContentType(contentType);response.setHeader("Content-disposition", new String(contentDisposition.getBytes("UTF-8"),"ISO8859-1"));try {InputStream is = new FileInputStream(filePath);OutputStream os = response.getOutputStream();int byteRead;byte[] buffer = new byte[1024];while ((byteRead = is.read(buffer)) != -1) {os.write(buffer, 0, byteRead);}os.flush();os.close();} catch (Exception e) {e.printStackTrace();}}/**** @param suffix 下载文件尾缀* @return 返回不同response.contentType*/public String getContentType(String suffix) {if (suffix.equals("txt")) {return "text/plain";} else if(suffix.equals("doc") || suffix.equals("docx")) {return "application/msword;charset=gb2312";} else if(suffix.equals("xls") || suffix.equals("xlsx")) {return "application/-excel";} else if(suffix.equals("pdf")) {return "application/pdf";}else if(suffix.equals("gif")){return "image/gif" ;}else if(suffix.equals("jpg")){return "image/jpeg" ;}else if(suffix.equals("htm")||suffix.equals("html")||suffix.equals("jsp")){return "text/html" ;}else if(suffix.equals("xml")){return "text/xml" ;}else if(suffix.equals("js")){return "application/x-javascript" ;}return "application/octet-stream";}public void init(FilterConfig config) throws ServletException {}}注:其中编码ISO8859-1不能乱改,否则出现解析路径错误或者下载文件出错。
java 导出excel数据的方法主题:Java 导出Excel 数据的方法引言:在开发Java应用程序时,经常需要将数据导出到Excel文件中。
Excel是一种常用的电子表格工具,可以对数据进行分析和可视化展示。
本文将介绍如何使用Java来导出Excel数据,以及实现这一功能的详细步骤。
1. 导入所需库首先,我们需要在Java项目中导入所需的库。
常用的库包括Apache POI和Apache POI-OOXML。
这些库提供了用于操作Excel 文件的类和方法。
2. 创建工作簿和工作表在Java中,我们通过HSSFWorkbook类创建一个新的Excel 工作簿。
然后,使用createSheet方法创建一个新的工作表对象。
我们可以为工作表指定名称,并将其附加到工作簿中。
3. 创建表头在工作表中,我们可以使用createRow方法创建一个新的行对象。
然后,使用createCell方法在行中创建单元格对象。
通过设置单元格的值,可以定义表头的内容。
4. 导出数据接下来,我们可以使用循环遍历数据集,并将数据写入Excel文件中。
每个数据项都可以被写入单元格对象中。
可以根据需要设置单元格的格式和样式。
5. 保存文件当所有数据都被写入Excel文件后,我们可以使用FileOutputStream类将工作簿中的数据保存到硬盘上的某个位置。
通过指定文件路径和文件名,可以将Excel文件保存在所需的位置。
6. 完整代码示例javaimport ermodel.HSSFWorkbook;import ermodel.*;import java.io.FileOutputStream;import java.util.List;public class ExcelExporter {public static void export(List<DataObject> data, String filePath) {try {Workbook workbook = new HSSFWorkbook();Sheet sheet = workbook.createSheet("Sheet 1");创建表头Row headerRow = sheet.createRow(0);Cell cell = headerRow.createCell(0);cell.setCellValue("Column 1");cell = headerRow.createCell(1);cell.setCellValue("Column 2");...导出数据int rowNum = 1;for (DataObject obj : data) {Row row = sheet.createRow(rowNum++);cell = row.createCell(0);cell.setCellValue(obj.getField1());cell = row.createCell(1);cell.setCellValue(obj.getField2());...}保存文件FileOutputStream fileOut = new FileOutputStream(filePath);workbook.write(fileOut);fileOut.close();System.out.println("Excel文件导出成功!");} catch (Exception e) {e.printStackTrace();}}}示例中,我们通过export方法将一个包含数据对象的列表导出到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的安全级别。
js引用本地excel数据-回复在JavaScript中引用本地Excel数据可能是许多开发人员经常遇到的问题之一。
本文将详细介绍如何使用JavaScript来读取本地的Excel文件并将其用于Web开发中。
在开始之前,我们需要明确一些前提条件。
首先,我们需要一个Excel文件,其中包含我们要引用的数据。
其次,我们需要一个用于处理Excel文件的JavaScript库。
有许多JavaScript库可以处理Excel文件,但我们将使用最流行和常用的库之一- SheetJS。
SheetJS是一个强大的库,可以读取和写入Excel 文件。
它不需要任何服务器端组件,完全在客户端执行。
首先,我们需要在项目中引入SheetJS库。
可以通过使用CDN(内容分发网络)或将库下载到本地来实现。
以下是用于引入SheetJS的CDN代码:<script src="现在,我们可以开始使用SheetJS库来读取本地的Excel文件。
下面是一步一步的说明:第一步:创建文件输入元素我们需要在HTML中创建一个文件输入元素,允许用户选择Excel文件。
可以使用以下代码创建文件输入元素:<input type="file" id="excelFile" />第二步:处理文件选择事件当用户选择Excel文件时,我们需要捕获该事件,并在事件处理程序中执行相应的操作。
可以使用以下代码来处理文件选择事件:document.getElementById('excelFile').addEventListener('change', handleFile, false);function handleFile(e) {获取选择的Excel文件var file = e.target.files[0];创建文件读取器var reader = new FileReader();设置读取完成后的回调函数reader.onload = function(e) {var data = new Uint8Array(e.target.result);var workbook = XLSX.read(data, {type: 'array'});处理Excel数据processExcel(workbook);};读取Excel文件reader.readAsArrayBuffer(file);}以上代码中的`handleFile()`函数将监听文件选择事件,并在文件读取完成后执行回调函数。
读到数据库,可以通过jxl来实现,可以把EXCEL文档上传到系统的上传目录下后,然后再取得这个文件,或者直接取得这个文件,对这个文件进行操作。
例子:public void addCustomerAssign(File file,SysExpo expo,SysUser user1)//添加客服中心数据{jxl.Workbook rwb = null;try{//构建Workbook对象, 只读Workbook对象//直接从本地文件创建Workbook//从输入流创建WorkbookInputStream is = new FileInputStream(file);rwb = Workbook.getWorkbook(is);String createTime = DateUtil.getDateTime( "yyyy-MM-dd HH:mm ",new Date()).toString();//Sheet(术语:工作表)就是Excel表格左下角的Sheet1,Sheet2,Sheet3但在程序中//Sheet的下标是从0开始//获取第一张Sheet表Sheet rs = rwb.getSheet(0);//获取Sheet表中所包含的总列数// int rsColumns = rs.getColumns();//获取Sheet表中所包含的总行数int rsRows = rs.getRows();//获取指定单元格的对象引用// rs.getCell(列,行);for(int i=1;i <rsRows;i++){//如第一行为属性项则从第二行开始取数据(int i=0 ;i <rsRows;i++)//for(int j=0;j <rsColumns;j++){//Cell cell = rs.getCell(j,i);// System.out.print(cell.getContents()+ " ");// }//Cell cell = rs.getCell(0,i).getContents()+ " ";String cell1= rs.getCell(0,i).getContents()+ " ";//序号String cell7 = rs.getCell(6,i).getContents()+ " ";//公司名称if(cell1!=null&&!cell1.equals( " ")&&cell7!=null&&!cell7.equals( " "))//判断当前行是否为有效行是插入否找下行{Company company = new Company();company.setName(rs.getCell(0,i).getContents()+ " ");//1名称company.setManager(rs.getCell(1,i).getContents()+ " ");//2法人}}}catch(Exception e){e.printStackTrace();}finally{//操作完成时,关闭对象,释放占用的内存空间rwb.close();}}法二:Jsp 中由Excel 导入MySQL数据库(2009-11-15 20:18:49)转载标签:jspmysqlexcelittomysql.jsp<%@ page contentType="text/html; charset=GB2312" %><html><head><title>文件上载</title></head><body><form action="exceltoexcel" method="post">选择文件1:<input type="file" name="excel" /><input type="submit" value="导入" /></form></body></html>db.javapackage tomysql;import java.sql.*;public class db {public Connection connstr = null;public ResultSet res = null;public PreparedStatement prase=null;static private String strUrl ="jdbc:mysql://localhost:3306/wangzhan?useUnicode=true&characterEncoding=gb2312";static private String strUser = "root";static private String strPwd = "7820067";public db(){try{//Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");//connstr = DriverManager.getConnection(//"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=BookStore",//"sa","7820067");Class.forName("com.mysql.jdbc.Driver");connstr = DriverManager.getConnection(strUrl, strUser, strPwd);}catch (SQLException ex){System.out.println(ex.getMessage() + "路径错误");}catch (ClassNotFoundException ex){System.out.println(ex.getMessage() + "驱动错误");}finally{System.out.println("成功了");}}public ResultSet executeQuery(String sql){try{Statement stmt=connstr.createStatement();res=stmt.executeQuery(sql);}catch(SQLException ex){System.out.println(ex.getMessage());}return res;}public PreparedStatement dosql(String sql){try{prase=connstr.prepareStatement(sql);}catch(Exception e){}return prase;}}excel.javapackage tomysql;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.util.*;import jxl.Sheet;import jxl.Workbook;public class excel {public List addCustomerAssign(File file)//添加客服中心数据{List ls=new ArrayList();jxl.Workbook rwb = null;try{//构建Workbook对象, 只读Workbook对象//直接从本地文件创建Workbook//从输入流创建WorkbookInputStream is = new FileInputStream(file);rwb = Workbook.getWorkbook(is);// String createTime = DateUtil.getDateTime( "yyyy-MM-dd HH:mm",new Date()).toString();//Sheet(术语:工作表)就是Excel表格左下角的Sheet1,Sheet2,Sheet3但在程序中//Sheet的下标是从0开始//获取第一张Sheet表Sheet rs = rwb.getSheet(0);//获取Sheet表中所包含的总列数// int rsColumns = rs.getColumns();//获取Sheet表中所包含的总行数int rsRows = rs.getRows();//获取指定单元格的对象引用// rs.getCell(列,行);for(int i=1;i <rsRows;i++){//如第一行为属性项则从第二行开始取数据(int i=0 ;i <rsRows;i++)//for(int j=0;j <rsColumns;j++){//Cell cell = rs.getCell(j,i);// System.out.print(cell.getContents()+ " ");// }//Cell cell = rs.getCell(0,i).getContents()+ " ";String cell1= rs.getCell(0,i).getContents()+ " ";//序号String cell7 = rs.getCell(1,i).getContents()+ " ";//公司名称String cell8 = rs.getCell(1,i).getContents()+ " ";//公司名称if(cell1!=null&&!cell1.equals( " ")&&cell7!=null&&!cell7.equals( " "))//判断当前行是否为有效行是插入否找下行{mynews ms=new mynews();ms.setTitle(rs.getCell(0,i).getContents());//1名称ms.setAuthor(rs.getCell(1,i).getContents());//2法人ms.setContent(rs.getCell(2,i).getContents());ls.add(ms);}}}catch(Exception e){e.printStackTrace();}finally{//操作完成时,关闭对象,释放占用的内存空间rwb.close();}return ls;}}into.javapackage tomysql;import java.util.*;import java.sql.*;import java.io.*;public class into {String sql="insert into mynews(title,author,content) values(?,?,?)"; db data=new db();public PreparedStatement prase=null;public Boolean insertexcel(mynews ms) {Boolean jiaqi=false;try{prase=data.dosql(sql);prase.setString(1, ms.getTitle()); prase.setString(2, ms.getAuthor()); prase.setString(3, ms.getContent()); prase.executeUpdate();jiaqi=true;}catch(Exception e){e.printStackTrace();}return jiaqi;}}mynews.javapackage tomysql;public class mynews {private int id;private String title;private String author;private String content;public String getAuthor() {return author;}public void setAuthor(String author) { this.author = author;}public String getContent() {return content;}public void setContent(String content) { this.content = content;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getTitle() {return title;}public void setTitle(String title) { this.title = title;}}---------------servlet---------------tomysqlservlet.javapackage tomysql;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.*;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class tomysqlservlet extends HttpServlet {public tomysqlservlet() {super();}public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {into in=new into();excel ex=new excel();String path=request.getParameter("excel");File file=new File(path);List ls=ex.addCustomerAssign(file);Iterator iter=ls.iterator();while(iter.hasNext()){mynews ms=(mynews)iter.next();if(in.insertexcel(ms))System.out.println("成功");elseSystem.out.println("失败");}}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{doGet(request, response);}public void init() throws ServletException {// Put your code here}}。
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里面有很多例子代码,可以很方便上手。
四.使用心得POI HSSF 的usermodel包把Excel文件映射成我们熟悉的结构,诸如Workbook、Sheet、Row、Cell等,它把整个结构以一组对象的形式保存在内存之中,便于理解,操作方便,基本上能够满足我们的要求,所以说这个是一个不错的选择。
1.创建工作簿 (WORKBOOK)HSSFWorkbook wb = new HSSFWorkbook();FileOutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);fileOut.close();2.创建工作表(SHEET)HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet1 = wb.createSheet("new sheet");HSSFSheet sheet2 = wb.createSheet("second sheet"); FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut);fileOut.close();3.创建单元格(CELL)HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("new sheet");HSSFRow row = sheet.createRow((short)0);HSSFCell cell = row.createCell((short)0);cell.setCellValue(1);row.createCell((short)1).setCellValue(1.2);row.createCell((short)2).setCellValue("This is a string");row.createCell((short)3).setCellValue(true);FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut);fileOut.close();4.创建指定单元格式的单元格HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("new sheet");HSSFRow row = sheet.createRow((short)0);HSSFCell cell = row.createCell((short)0);cell.setCellValue(new Date());HSSFCellStyle cellStyle = wb.createCellStyle();cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); cell = row.createCell((short)1);cell.setCellValue(new Date());cell.setCellStyle(cellStyle);FileOutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);fileOut.close();5. 单元格的不同格式HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("new sheet");HSSFRow row = sheet.createRow((short)2);row.createCell((short) 0).setCellValue(1.1);row.createCell((short) 1).setCellValue(new Date());row.createCell((short) 2).setCellValue("a string");row.createCell((short) 3).setCellValue(true);row.createCell((short) 4).setCellType(HSSFCell.CELL_TYPE_ERROR);FileOutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);fileOut.close();6.单元格的不通对齐方式public static void main(String[] args) throws IOException{HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("new sheet");HSSFRow row = sheet.createRow((short) 2);createCell(wb, row, (short) 0, HSSFCellStyle.ALIGN_CENTER);createCell(wb, row, (short) 1, HSSFCellStyle.ALIGN_CENTER_SELECTION);createCell(wb, row, (short) 2, HSSFCellStyle.ALIGN_FILL);createCell(wb, row, (short) 3, HSSFCellStyle.ALIGN_GENERAL);createCell(wb, row, (short) 4, HSSFCellStyle.ALIGN_JUSTIFY);createCell(wb, row, (short) 5, HSSFCellStyle.ALIGN_LEFT);createCell(wb, row, (short) 6, HSSFCellStyle.ALIGN_RIGHT);FileOutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);fileOut.close();}private static void createCell(HSSFWorkbook wb, HSSFRow row, short column, short align) {HSSFCell cell = row.createCell(column);cell.setCellValue("Align It");HSSFCellStyle cellStyle = wb.createCellStyle();cellStyle.setAlignment(align);cell.setCellStyle(cellStyle);}7.单元格的边框设置HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("new sheet");HSSFRow row = sheet.createRow((short) 1);HSSFCell cell = row.createCell((short) 1);cell.setCellValue(4);HSSFCellStyle style = wb.createCellStyle();style.setBorderBottom(HSSFCellStyle.BORDER_THIN);style.setBottomBorderColor(HSSFColor.BLACK.index);style.setBorderLeft(HSSFCellStyle.BORDER_THIN);style.setLeftBorderColor(HSSFColor.GREEN.index);style.setBorderRight(HSSFCellStyle.BORDER_THIN);style.setRightBorderColor(HSSFColor.BLUE.index);style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM_DASHED);style.setTopBorderColor(HSSFColor.BLACK.index);cell.setCellStyle(style);FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut);fileOut.close();8.填充和颜色设置HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("new sheet");HSSFRow row = sheet.createRow((short) 1);HSSFCellStyle style = wb.createCellStyle();style.setFillBackgroundColor(HSSFColor.AQUA.index);style.setFillPattern(HSSFCellStyle.BIG_SPOTS);HSSFCell cell = row.createCell((short) 1);cell.setCellValue("X");cell.setCellStyle(style);style = wb.createCellStyle();style.setFillForegroundColor(HSSFColor.ORANGE.index);style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);cell = row.createCell((short) 2);cell.setCellValue("X");cell.setCellStyle(style);FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut);fileOut.close();9.合并单元格操作HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("new sheet");HSSFRow row = sheet.createRow((short) 1);HSSFCell cell = row.createCell((short) 1);cell.setCellValue("This is a test of merging");sheet.addMergedRegion(new Region(1,(short)1,1,(short)2));FileOutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);fileOut.close();9.1合并单元格边框的解决办法private void setRegionStyle(HSSFSheet sheet, Region region , HSSFCellStyle cs) { int toprowNum = region.getRowFrom();for (int i = region.getRowFrom(); i <= region.getRowTo(); i ++) {HSSFRow row = HSSFCellUtil.getRow(i, sheet);for (int j = region.getColumnFrom(); j <= region.getColumnTo(); j++) { HSSFCell cell = HSSFCellUtil.getCell(row, (short)j);cell.setCellStyle(cs);}}}10.字体设置HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("new sheet");HSSFRow row = sheet.createRow((short) 1);HSSFFont font = wb.createFont();font.setFontHeightInPoints((short)24);font.setFontName("Courier New");font.setItalic(true);font.setStrikeout(true);HSSFCellStyle style = wb.createCellStyle();style.setFont(font);HSSFCell cell = row.createCell((short) 1);cell.setCellValue("This is a test of fonts");cell.setCellStyle(style);FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut);fileOut.close();11.自定义颜色Java代码HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet();HSSFRow row = sheet.createRow((short) 0);HSSFCell cell = row.createCell((short) 0);cell.setCellValue("Default Palette");HSSFCellStyle style = wb.createCellStyle();style.setFillForegroundColor(HSSFColor.LIME.index);style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);HSSFFont font = wb.createFont();font.setColor(HSSFColor.RED.index);style.setFont(font);cell.setCellStyle(style);FileOutputStream out = new FileOutputStream("default_palette.xls");wb.write(out);out.close();cell.setCellValue("Modified Palette");HSSFPalette palette = wb.getCustomPalette();palette.setColorAtIndex(HSSFColor.RED.index,(byte) 153, //RGB red (0-255)(byte) 0, //RGB green(byte) 0 //RGB blue);palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);out = new FileOutputStream("modified_palette.xls");wb.write(out);out.close();12.读和重写EXCEL文件POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("workbook.xls")); HSSFWorkbook wb = new HSSFWorkbook(fs);HSSFSheet sheet = wb.getSheetAt(0);HSSFRow row = sheet.getRow(2);HSSFCell cell = row.getCell((short)3);if (cell == null)cell = row.createCell((short)3);cell.setCellType(HSSFCell.CELL_TYPE_STRING);cell.setCellValue("a test");FileOutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);fileOut.close();13.在EXCEL单元格中使用自动换行HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet s = wb.createSheet();HSSFRow r = null;HSSFCell c = null;HSSFCellStyle cs = wb.createCellStyle();HSSFFont f = wb.createFont();HSSFFont f2 = wb.createFont();cs = wb.createCellStyle();cs.setFont( f2 );cs.setWrapText( true );r = s.createRow( (short) 2 );r.setHeight( (short) 0x349 );c = r.createCell( (short) 2 );c.setCellType( HSSFCell.CELL_TYPE_STRING );c.setCellValue( "Use \n with word wrap on to create a new line" );c.setCellStyle( cs );s.setColumnWidth( (short) 2, (short) ( ( 50 * 8 ) / ( (double) 1 / 20 ) ) ); FileOutputStream fileOut = new FileOutputStream( "workbook.xls" );wb.write( fileOut );fileOut.close();14.数字格式自定义HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("format sheet");HSSFCellStyle style;HSSFDataFormat format = wb.createDataFormat();HSSFRow row;HSSFCell cell;short rowNum = 0;short colNum = 0;row = sheet.createRow(rowNum++);cell = row.createCell(colNum);cell.setCellValue(11111.25);style = wb.createCellStyle();style.setDataFormat(format.getFormat("0.0"));cell.setCellStyle(style);row = sheet.createRow(rowNum++);cell = row.createCell(colNum);cell.setCellValue(11111.25);style = wb.createCellStyle();style.setDataFormat(format.getFormat("#,##0.0000"));cell.setCellStyle(style);FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut);fileOut.close();HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("format sheet");HSSFCellStyle style;HSSFDataFormat format = wb.createDataFormat();HSSFRow row;HSSFCell cell;short rowNum = 0;short colNum = 0;row = sheet.createRow(rowNum++);cell = row.createCell(colNum);cell.setCellValue(11111.25);style = wb.createCellStyle();style.setDataFormat(format.getFormat("0.0"));cell.setCellStyle(style);row = sheet.createRow(rowNum++);cell = row.createCell(colNum);cell.setCellValue(11111.25);style = wb.createCellStyle();style.setDataFormat(format.getFormat("#,##0.0000"));cell.setCellStyle(style);FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut);fileOut.close();15.调整工作单位置HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("format sheet");HSSFPrintSetup ps = sheet.getPrintSetup();sheet.setAutobreaks(true);ps.setFitHeight((short)1);ps.setFitWidth((short)1); // Create various cells and rows for spreadsheet. FileOutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);fileOut.close();16.设置打印区域HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("Sheet1");wb.setPrintArea(0, "$A$1:$C$2");FileOutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);fileOut.close();17.标注脚注HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("format sheet");HSSFFooter footer = sheet.getFooter()footer.setRight( "Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages() ); FileOutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);fileOut.close();18.使用方便的内部提供的函数HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet1 = wb.createSheet( "new sheet" );HSSFRow row = sheet1.createRow( (short) 1 );HSSFRow row2 = sheet1.createRow( (short) 2 );HSSFCell cell = row.createCell( (short) 1 );cell.setCellValue( "This is a test of merging" );Region region = new Region( 1, (short) 1, 4, (short) 4 );sheet1.addMergedRegion( region );final short borderMediumDashed = HSSFCellStyle.BORDER_MEDIUM_DASHED; HSSFRegionUtil.setBorderBottom( borderMediumDashed,region, sheet1, wb );HSSFRegionUtil.setBorderTop( borderMediumDashed,region, sheet1, wb );HSSFRegionUtil.setBorderLeft( borderMediumDashed,region, sheet1, wb );HSSFRegionUtil.setBorderRight( borderMediumDashed,region, sheet1, wb );HSSFRegionUtil.setBottomBorderColor(HSSFColor.AQUA.index, region, sheet1, wb); HSSFRegionUtil.setTopBorderColor(HSSFColor.AQUA.index, region, sheet1, wb); HSSFRegionUtil.setLeftBorderColor(HSSFColor.AQUA.index, region, sheet1, wb); HSSFRegionUtil.setRightBorderColor(HSSFColor.AQUA.index, region, sheet1, wb); HSSFCellStyle style = wb.createCellStyle();style.setIndention((short)4);HSSFCellUtil.createCell(row, 8, "This is the value of the cell", style);HSSFCell cell2 = HSSFCellUtil.createCell( row2, 8, "This is the value of the cell"); HSSFCellUtil.setAlignment(cell2, wb, HSSFCellStyle.ALIGN_CENTER);FileOutputStream fileOut = new FileOutputStream( "workbook.xls" );wb.write( fileOut );fileOut.close();19.在工作单中移动行,调整行的上下位置HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("row sheet");sheet.shiftRows(5, 10, -5);FileOutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);fileOut.close();20.选种指定的工作单HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("row sheet");sheet.setSelected(true);FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut);fileOut.close();21.工作单的放大缩小HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet1 = wb.createSheet("new sheet");sheet1.setZoom(3,4);FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut);fileOut.close();22.头注和脚注HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("new sheet");HSSFHeader header = sheet.getHeader();header.setCenter("Center Header");header.setLeft("Left Header");header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") +HSSFHeader.fontSize((short) 16) + "Right w/ Stencil-Normal Italic font and size 16"); FileOutputStream fileOut = new FileOutputStream("workbook.xls");wb.write(fileOut);fileOut.close();23.图片的使用//先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();BufferedImage bufferImg = ImageIO.read(new File("ok.jpg"));ImageIO.write(bufferImg,"jpg",byteArrayOut);//读进一个excel模版FileInputStream fos = new FileInputStream(filePathName+"/stencil.xlt");fs = new POIFSFileSystem(fos);//创建一个工作薄HSSFWorkbook wb = new HSSFWorkbook(fs);HSSFSheet sheet = wb.getSheetAt(0);HSSFPatriarch patriarch = sheet.createDrawingPatriarch();HSSFClientAnchor anchor = new HSSFClientAnchor(0,0,1023,255,(short) 0,0,(short)10,10);patriarch.createPicture(anchor , wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG)); //先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArrayByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();BufferedImage bufferImg = ImageIO.read(new File("ok.jpg"));ImageIO.write(bufferImg,"jpg",byteArrayOut);//读进一个excel模版FileInputStream fos = new FileInputStream(filePathName+"/stencil.xlt");fs = new POIFSFileSystem(fos);//创建一个工作薄HSSFWorkbook wb = new HSSFWorkbook(fs);HSSFSheet sheet = wb.getSheetAt(0);HSSFPatriarch patriarch = sheet.createDrawingPatriarch();HSSFClientAnchor anchor = new HSSFClientAnchor(0,0,1023,255,(short) 0,0,(short)10,10);patriarch.createPicture(anchor , wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG));//-------------------------------以上实例代码均来自官方网站//-------------------------------POI中使用的颜色是用颜色索引来实现,如下:/** 颜色对照表数字代表颜色索引8: BLACK60: BROWN59: OLIVE_GREEN58: DARK_GREEN56: DARK_TEAL18: DARK_BLUE32: DARK_BLUE62: INDIGO63: GREY_80_PERCENT 53: ORANGE19: DARK_YELLOW 17: GREEN21: TEAL38: TEAL12: BLUE39: BLUE54: BLUE_GREY23: GREY_50_PERCENT 10: RED52: LIGHT_ORANGE 50: LIME57: SEA_GREEN49: AQUA48: LIGHT_BLUE20: VIOLET36: VIOLET55: GREY_40_PERCENT 14: PINK33: PINK51: GOLD13: YELLOW34: YELLOW11: BRIGHT_GREEN35: BRIGHT_GREEN15: TURQUOISE35: TURQUOISE16: DARK_RED37: DARK_RED40: SKY_BLUE61: PLUM25: PLUM22: GREY_25_PERCENT45: ROSE43: LIGHT_YELLOW42: LIGHT_GREEN41: LIGHT_TURQUOISE27:LIGHT_TURQUOISE44: PALE_BLUE46: LAVENDER9: WHITE24: CORNFLOWER_BLUE26: LEMON_CHIFFON25: MAROON28: ORCHID29: CORAL30: ROYAL_BLUE31: LIGHT_CORNFLOWER_BLUE五、应用实例:<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %> <%@ page import="ng.*,computer.*"%><html><head><title>计算机设备管理</title><%GetData gd=new GetData();%></head><form name="form1" action="SaveData.jsp"><table border="0" cellspacing="1" cellpadding="2" width="97%" align="center" bgcolor="#F6F6F6"> <tr><td colspan="5"><div align="center"><img src="images/text01.jpg" align="center"></div></td></tr> <tr><td colspan="5"><hr></td></tr><tr><td width="15%"><div align="right">设备编号</div></td></tr><tr><td colspan="5"><div align="center"><input name="btnDo" type="submit" value="数据提交"> <input name="btnReset" type="reset" value="重新输入"> <input name="btnOutToExcel" type="button" value="导出到Excel" onClick="clickForOutToExcel();"></div></td></tr><tr><td colspan="5"><hr></td></tr></table><input name="Page_Mark" type="hidden" value="Maintain"></form><form name="form2" action="JSPExcel.jsp"><input name="GetOrPut" type="hidden" value=""></form><script language=javascript>function clickForOutToExcel(){document.form2.GetOrPut.value="PutMaintain";alert("维修设备清单成功导出为EXCEL文件!\r\r请查看C盘根目录下的:维修清单.xls"); document.form2.submit();}</script></html>六、处理有EXCEL导入导出要求的JSP文件(JSPExcel.jsp)<%@ page contentType="text/html;charset=gbk"%><%@ page import="ng.*,computer.*"%><html><head></head><body><%String gp=request.getParameter("GetOrPut");String gf=Pool.toChinese(request.getParameter("GFF")); GetOrWriteExcel gwe=new GetOrWriteExcel();if (pareTo("Put")==0) {try{gwe.AllEquipToExcel();%><jsp:forward page="Equip.jsp"><jsp:param name="" value=""/></jsp:forward><%}catch(Exception ep){System.out.println(ep);}}else if (pareTo("Get")==0) {try{gwe.GetEquipFromExcel(gf);%><jsp:forward page="Equip.jsp"><jsp:param name="" value=""/></jsp:forward><%}catch(Exception ep){System.out.println(ep);}}else if (pareTo("PutDis")==0) {try{gwe.DisToExcel();%><jsp:forward page="Distribute.jsp"><jsp:param name="" value=""/></jsp:forward><%}catch(Exception ep){System.out.println(ep);}}else if (pareTo("PutMaintain")==0) {try{gwe.MaintainToExcel();%><jsp:forward page="Maintain.jsp"><jsp:param name="" value=""/></jsp:forward><%}catch(Exception ep){System.out.println(ep);}}else if (pareTo("PutTrash")==0) { try{gwe.TrashToExcel();%><jsp:forward page="Trash.jsp"><jsp:param name="" value=""/></jsp:forward><%}catch(Exception ep){System.out.println(ep);}}else {System.out.println("GETORPUT的值是空的!");}%></body></html>七、Javabean中专门处理EXCEL的导入导出的类:GetOrWriteExcel.java package computer;import java.io.*;import java.sql.Connection;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import ermodel.*;import org.apache.poi.hssf.util.HSSFColor;import org.apache.poi.poifs.filesystem.POIFSFileSystem;public class GetOrWriteExcel {Pool pl;Connection cn;public GetOrWriteExcel(){try{pl=new Pool();//在办公室通过WEB操作数据库cn=pl.getConnection();//在办公室用Test测试数据库操作//cn=pl.getConnectForTest();//在家测试数据库//cn=pl.getConnectAtHome();if (cn==null){System.out.println("数据库连接为空");}} catch(Exception ex){System.out.println(ex);}}public void AllEquipToExcel(){String sqlStr="select * from Equip_View";String fname="c:\\设备清单.xls";try {DataToExcel(sqlStr,fname);System.out.println("所有设备导入到Excel成功!"); } catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** 从Excel中导入设备列表,参数gf表示要导入的excel文件名*/public void GetEquipFromExcel(String gf)throws IOException{try{POIFSFileSystem fs=new POIFSFileSystem(new FileInputStream(gf));HSSFWorkbook wb=new HSSFWorkbook(fs);HSSFSheet sheet=wb.getSheetAt(0);HSSFRow row;int count=0;count=sheet.getPhysicalNumberOfRows();//数据库操作try{cn.setAutoCommit(false);Statement st=cn.createStatement();String sqlStr="";for (int i=1;i<count;i++){row=sheet.getRow(i);sqlStr="INSERT INTO Equip(EquipID,Price,BuyDate,ETypeID,DealerID,CPU,HD,MEMORY,DISPLAY,MAINBOARD,EState,Other,Remark,Spec)VALUES(";sqlStr += "'";sqlStr += row.getCell((short)0).toString().trim();sqlStr += "','";sqlStr += Float.parseFloat(row.getCell((short)1).toString()); sqlStr += "','";sqlStr += row.getCell((short)2).toString().substring(0, 10); sqlStr += "','";sqlStr += row.getCell((short)3).toString().trim();sqlStr += "','";sqlStr += row.getCell((short)4).toString().trim();sqlStr += "','";sqlStr += row.getCell((short)5).toString().trim();sqlStr += "','";sqlStr += row.getCell((short)6).toString().trim();sqlStr += "','";sqlStr += row.getCell((short)7).toString().trim();sqlStr += "','";sqlStr += row.getCell((short)8).toString().trim();sqlStr += "','";sqlStr += row.getCell((short)9).toString().trim();sqlStr += "','";sqlStr += row.getCell((short)10).toString().trim();sqlStr += "','";sqlStr += row.getCell((short)11).toString().trim();sqlStr += "','";sqlStr += row.getCell((short)12).toString().trim();sqlStr += "','";sqlStr += row.getCell((short)13).toString().trim();sqlStr += "')";//System.out.println(sqlStr);st.addBatch(sqlStr);//st.execute(sqlStr);//System.out.println(sqlStr);}st.executeBatch();mit();cn.setAutoCommit(true);st.close();System.out.println("从Excel中成功批量导入设备!");}catch(Exception se){System.out.println("向Equip表中批量存入数据时出错,错误代码:" + se); }}catch (FileNotFoundException e) {e.printStackTrace();}}public void DisToExcel(){String sqlStr="select * from Distribute_View";String fname="c:\\领用清单.xls";try {DataToExcel(sqlStr,fname);System.out.println("所有领用设备导入到Excel成功!"); } catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void MaintainToExcel(){String sqlStr="select * from EquipMaintain_View";String fname="c:\\维修清单.xls";try {DataToExcel(sqlStr,fname);System.out.println("所有维修记录导入到Excel成功!"); } catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void TrashToExcel(){String sqlStr="select * from Trash_View";String fname="c:\\报废清单.xls";try {DataToExcel(sqlStr,fname);System.out.println("所有维修记录导入到Excel成功!");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** 从数据库将数据导出到EXCEL文件的通用函数,参数sqlStr是传来的sql语句,filename是要保存的文件名与路径 */public void DataToExcel(String sqlStr,String filename) throws IOException{ResultSet rs = null;ResultSetMetaData rsmeta=null;Statement st = null;try{String[] title;HSSFWorkbook wb=new HSSFWorkbook();HSSFSheet sheet=wb.createSheet("数据清单");HSSFRow row=sheet.createRow((short)0);//第一行显示字段名称st=cn.createStatement();rs = st.executeQuery(sqlStr);rsmeta=rs.getMetaData();int numofCols=rsmeta.getColumnCount();title=new String[numofCols];for (int i=0;i<numofCols;i++){title[i]=rsmeta.getColumnName(i+1);row.createCell((short)i).setCellValue(title[i]);}//以下显示数据int k=1;while(rs.next()){row=sheet.createRow((short)k);for (int j=1;j<=numofCols;j++){row.createCell((short)(j-1)).setCellValue(rs.getString(j)); }k++;}FileOutputStream fileOut=new FileOutputStream(filename);wb.write(fileOut);fileOut.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace();} finally {try {rs.close();st.close();} catch (Exception e) {e.printStackTrace();}}}}。