js如何导出exel文件

js如何导出exel文件,第1张

简单的办法:使用js生成一个table,可以直接复制到excel中,网上有很多表格插件。

复杂的办法:js传递数据到服务器,服务器生成表格后返回一个下载链接。

JavaScript一种直译式脚本语言,是一种动态类型、弱类型、基于原型的语言,内置支持类型。它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在HTML(标准通用标记语言下的一个应用)网页上使用,用来给HTML网页增加动态功能。

在1995年时,由Netscape公司的Brendan Eich,在网景导航者浏览器上首次设计实现而成。因为Netscape与Sun合作,Netscape管理层希望它外观看起来像Java,因此取名为JavaScript。但实际上它的语法风格与Self及Scheme较为接近。

为了取得技术优势,微软推出了JScript,CEnvi推出ScriptEase,与JavaScript同样可在浏览器上运行。为了统一规格,因为JavaScript兼容于ECMA标准,因此也称为ECMAScript。

Microsoft Excel是微软公司的办公软件Microsoft office的组件之一,是由Microsoft为Windows和Apple Macintosh *** 作系统的电脑而编写和运行的一款试算表软件。Excel 是微软办公套装软件的一个重要的组成部分,它可以进行各种数据的处理、统计分析和辅助决策 *** 作,广泛地应用于管理、统计财经、金融等众多领域。

自己试试吧:

<!doctype html public "-//w3c//dtd html 40 transitional//en">

<html>

<head>

<title> new document </title>

<meta name="generator" content="editplus">

<meta name="author" content="">

<meta name="keywords" content="">

<meta name="description" content="">

<style>

body{

background-color:red;

}

divsel{

font-size:15px;

color:green;

}

</style>

<SCRIPT LANGUAGE="JavaScript">

<!--

windowonload = function(){

var sheet =documentstyleSheets[0];

var rules = sheetcssRules || sheetrules;//

var rule = rules[0];

alert(ruleselectorText)

alert(rulestylecssText)

rule = rules[1];

alert(ruleselectorText)

alert(rulestylecssText)

}

//-->

</SCRIPT>

</head>

<body>

</body>

</html>

您可以使用SpreadJS的搜索功能来在多个sheet页中搜索内容。您可以在SpreadJS的“搜索”面板中输入您要搜索的内容,然后点击“搜索”按钮,SpreadJS将会在所有sheet页中搜索您输入的内容,并将搜索结果列出来,您可以点击搜索结果中的每一项,SpreadJS会自动跳转到该项所在的sheet页。

之前选择用 jquery-table2excel 导出后用office打开会提示“文件格式和扩展名不匹配”(如下图所示),虽然点击“是”,或者使用wps就可以正常打开,但毕竟是政府项目,所以决定另寻方法。而 SheetJS 是受微软信任的(官网上写Trusted by Microsoft in Office 365),导出的表格用office可以正常打开且功能强大,潘嘉诚的vue-element-admin也在用。

读取、编辑和导出表格

官网: >

--------------------------------------------------------

我建议你还是通过后台来处理,用JS的话,客户端压力太大,容易导致内存溢出,浏览器崩溃。

我用Java语言,通过jxl以及poi两种API给你写了例子,分别是用jxl读写excel文件,用poi读写excel文件。希望对你有帮助。(需要下载jxl和poi的jar包)

import javaioFileInputStream;

import javaioFileOutputStream;

import javaioIOException;

import javautilArrayList;

import javautilHashMap;

import javautilList;

import javautilMap;

import jxlCell;

import jxlSheet;

import jxlWorkbook;

import jxlformatColour;

import jxlformatUnderlineStyle;

import jxlwriteLabel;

import jxlwriteWritableCellFormat;

import jxlwriteWritableFont;

import jxlwriteWritableSheet;

import jxlwriteWritableWorkbook;

import orgapachepoihssfusermodelHSSFCell;

import orgapachepoihssfusermodelHSSFRichTextString;

import orgapachepoihssfusermodelHSSFRow;

import orgapachepoihssfusermodelHSSFSheet;

import orgapachepoihssfusermodelHSSFWorkbook;

import orgapachepoipoifsfilesystemPOIFSFileSystem;

public class ExcelUtil {

/

@param args

@throws IOException

/

public static void main(String[] args) throws IOException {

String outFile = "D:/workspace/JavaStudy/src/util/excel/testxls";

ExcelUtilwriteExcelByJXL(outFile, null);

}

/

@title: readExcelByJXL

@description: 通过jxl读取excel文件

@author yu ren tian

@email yurentian@163com

@param excelFile

@return

@throws IOException

/

private static List readExcelByJXL(String excelFile) throws IOException {

List rtn = new ArrayList();

FileInputStream fileInputStream = null;

try {

fileInputStream = new FileInputStream(excelFile);

Workbook excelWorkBook = WorkbookgetWorkbook(fileInputStream);

Sheet sheet = excelWorkBookgetSheet(0);

int m = sheetgetRows();

int n = sheetgetColumns();

for (int i = 1; i < m; i++) {

Map map = new HashMap();

for (int j = 0; j < n; j++) {

Cell cell = sheetgetCell(j, i);

String cellContent = cellgetContents();

switch (j) {

case 0:

mapput("studentName", cellContent);

break;

case 1:

mapput("Chinese", cellContent);

break;

case 2:

mapput("Math", cellContent);

break;

case 3:

mapput("English", cellContent);

break;

case 4:

mapput("assess", cellContent);

break;

}

}

rtnadd(map);

}

} catch (Exception e) {

eprintStackTrace();

} finally {

if (null != fileInputStream) {

fileInputStreamclose();

}

return rtn;

}

}

/

@title: writeExcelByJXL

@description: 通过jxl写入excel文件

@author yu ren tian

@email yurentian@163com

@param outFile

@param list

@throws IOException

/

private static void writeExcelByJXL(String outFile, List list)

throws IOException {

WritableWorkbook wwb;

FileOutputStream fos;

try {

fos = new FileOutputStream(outFile);

// wwb = WorkbookcreateWorkbook(file);

wwb = WorkbookcreateWorkbook(fos);

WritableSheet sheet = wwbcreateSheet("test", 0);

// 设置单元格的文字格式

WritableFont wf = new WritableFont(WritableFontARIAL, 12,

WritableFontNO_BOLD, false, UnderlineStyleNO_UNDERLINE,

ColourBLUE);

WritableCellFormat wcf = new WritableCellFormat(wf);

//wcfsetBackground(ColourGREEN);

wcfsetBackground(new CustomColor(11, "", 0, 0, 0));

for (int i = 0; i < 10; i++) {

Label label = new Label(i, 0, i + "", wcf);

sheetaddCell(label);

}

wwbwrite();

wwbclose();

fosclose();

} catch (Exception e) {

eprintStackTrace();

}

}

/

@title: readExcelByPOI

@description: 通过poi读取excel文件

@author yu ren tian

@email yurentian@163com

@param excelFile

@return

@throws IOException

/

private static List readExcelByPOI(String excelFile) throws IOException {

List rtn = new ArrayList();

FileInputStream fin = null;

try {

fin = new FileInputStream(excelFile);

POIFSFileSystem fs = new POIFSFileSystem(fin);

HSSFWorkbook wb = new HSSFWorkbook(fs);

HSSFSheet sheet = wbgetSheetAt(0);

int m = sheetgetLastRowNum() - sheetgetFirstRowNum() + 1;

int n = 5;

for (int i = 1; i < m; i++) {

Map map = new HashMap();

for (int j = 0; j < n; j++) {

HSSFCell cell = sheetgetRow(i)getCell((short) j);

int type = cellgetCellType();

String cellContentString = null;

double cellContentDouble = 0;

if (type == 1) {

cellContentString = cellgetRichStringCellValue()

getString();

Systemoutprintln("cellContentString="

+ cellContentString);

} else if (type == 0) {

cellContentDouble = cellgetNumericCellValue();

Systemoutprintln("cellContentDouble="

+ cellContentDouble);

}

Systemoutprintln("j=" + j);

switch (j) {

case 0:

mapput("studentName", cellContentString);

break;

case 1:

mapput("Chinese", new Double(cellContentDouble));

break;

case 2:

mapput("Math", new Double(cellContentDouble));

break;

case 3:

mapput("English", new Double(cellContentDouble));

break;

case 4:

mapput("assess", cellContentString);

break;

}

}

}

} catch (Exception e) {

eprintStackTrace();

} finally {

if (fin != null) {

finclose();

}

return rtn;

}

}

/

@title: writeExcelByPOI

@description: 通过poi写入excel

@author yu ren tian

@email yurentian@163com

@param outFile

@param list

@throws IOException

/

private static void writeExcelByPOI(String outFile, List list)

throws IOException {

FileOutputStream fos = new FileOutputStream(outFile);

HSSFWorkbook wb = new HSSFWorkbook();

for (int sheetCount = 0; sheetCount < 5; sheetCount++) {

HSSFSheet sheet = wbcreateSheet("组织" + (sheetCount + 1));

for (int rowCount = 0; rowCount < 10; rowCount++) {

for (int columnCount = 0; columnCount < 10; columnCount++) {

HSSFRow row = sheetcreateRow(rowCount);

HSSFCell cell = rowcreateCell(new Short(columnCount + ""));

HSSFRichTextString richTextString = new HSSFRichTextString(

"行=" + rowCount + " 列=" + columnCount);

cellsetCellValue(richTextString);

}

}

}

wbwrite(fos);

}

}

--------------------------------------------------------

我猜你的变量“startcol”、“endcol”的值都是整数。

”Columns(1)“、”Columns("A:B")“这两种方式可以,但是”Columns("1:2")“不行。

可以这样

ExcelSheetActiveSheetRange(ExcelSheetActiveSheetColumns(startcol), ExcelSheetActiveSheetColumns(endcol))ColumnWidth = 15

一、 直接拷贝整个表格到EXCEL中二、 通过遍历表格,给EXCEL中相应的单元格赋值。三、 把表格中的内容提取出来,利用IE的另存为csv的格式。各方法的好处:1 直接拷贝表格,能够保留表格中的原有的格式,比如,列,行的合并,对齐方式,底色等等,2 通过遍历表格,比较灵活,可以遍历表格某些需要部分的内容。3 利用IE的另存为,不用创建ActiveXObject对象,可以处理表格合并方面的问题。各方法的缺点:1 可能d出脚本错误:Automation不能创建对象。解决方法:启用IE安全设置中的:对没有标记为安全的ActiveX控件进行初始化和脚本运行。由于整个表格复制到EXCEL中,给表格加个标题,并加入到EXCEL中可能会遇到麻烦。解决方法:首先在表格中加入第一行<tr><td colspan="x" align="center">&</td></tr>X,表示整个表格的列数,复制完整个表格后,加如下代码,oSheet为当前活动的sheetoSheetRange(oSheetCells(1, 1), oSheetCells(1, x))value = "表格标题";//设置标题oSheetRows(1)FontSize = 16; //设置文字大小oSheetRows(1)FontName = "宋体";//设置文字字体注:以下属性我没用着,可能有用,也可能会报错oSheetRange(oSheetCells(1,1), oSheetCells(1,14))mergecells=true; //合并单元格oSheetRange(oSheetCells(1,1), oSheetCells(1,14))InteriorColorIndex=6;//设置底色oSheetRange(oSheetCells(1,1), oSheetCells(1,14))FontColorIndex=5;//设置字体色oSheetRows(1)RowHeight=20; //设置列高oSheetCells(iRow,iCol)Halignment=’2’//设置字体居中2 可能d出脚本错误:Automation不能创建对象(解决方法如上)。表格内容写入到EXCEL中无表格线(未解决)且有单元格合并时会有问题,解决方法:合并单元格后再写数据。oSheetRange(oSheetCells(1,1), oSheetCells(1,14))mergecells=true; //合并单元格3 表格内容写入到EXCEL中无表格线(未解决)表格格式复杂时,会有问题,(rowspan>1 or colspan>1),解决方法:一般都是表头格式比较复杂,可先把表头写死,然后再循环写其他数据。代码如下:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 40 Transitional//EN"><HTML><HEAD><TITLE> New Document </TITLE>

<META NAME="Generator" CONTENT="EditPlus">

<META NAME="Author" CONTENT="">

<META NAME="Keywords" CONTENT="">

<META NAME="Description" CONTENT="">

</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>bbb</td><td>ccc</td><td>ddd</td><td>eee</td></tr><tr><td>AAA</td><td>BBB</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 = documentgetElementById(tableid);var oXL = new ActiveXObject("ExcelApplication");//创建AX对象excelvar oWB = oXLWorkbooksAdd();//获取workbook对象var oSheet = oWBActiveSheet;//激活当前sheetvar sel = documentbodycreateTextRange();selmoveToElementText(curTbl);//把表格中的内容移到TextRange中selselect();//全选TextRange中内容selexecCommand("Copy");//复制TextRange中内容oSheetPaste();//粘贴到活动的EXCEL中oXLVisible = true;//设置excel可见属性}function method2(tableid) //读取表格中每个单元到EXCEL中

{var curTbl = documentgetElementById(tableid);var oXL = new ActiveXObject("ExcelApplication");//创建AX对象excelvar oWB = oXLWorkbooksAdd();//获取workbook对象var oSheet = oWBActiveSheet;//激活当前sheetvar Lenr = curTblrowslength;//取得表格行数for (i = 0; i < Lenr; i++){var Lenc = curTblrows(i)cellslength;//取得每行的列数for (j = 0; j < Lenc; j++){oSheetCells(i + 1, j + 1)value = curTblrows(i)cells(j)innerText;//赋值}}oXLVisible = true;//设置excel可见属性}function getXlsFromTbl(inTblId, inWindow) {try {var allStr = "";var curStr = "";//alert("getXlsFromTbl");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("导出发生异常:" + ename + "->" + edescription + "!");}}

//---------------------------------------------

function getTblData(inTbl, inWindow) {var rows = 0;//alert("getTblData is " + inWindow);var tblDocument = document;if (!!inWindow && inWindow != "") {if (!documentall(inWindow)) {return null;}else {tblDocument = eval(inWindow)document;}}var curTbl = tblDocumentgetElementById(inTbl);var outStr = "";if (curTbl != null) {for (var j = 0; j < curTblrowslength; j++) {//alert("j is " + j);for (var i = 0; i < curTblrows[j]cellslength; i++) {//alert("i is " + i);if (i == 0 && rows > 0) {outStr += " ";rows -= 1;}outStr += curTblrows[j]cells[i]innerText + " ";if (curTblrows[j]cells[i]colSpan > 1) {for (var k = 0; k < curTblrows[j]cells[i]colSpan - 1; k++) {outStr += " ";}}if (i == 0) {if (rows == 0 && curTblrows[j]cells[i]rowSpan > 1) {rows = curTblrows[j]cells[i]rowSpan - 1;}}}outStr += " ";}}else {outStr = null;alert(inTbl + "不存在!");}return outStr;}function getExcelFileName() {var d = new Date();var curYear = dgetYear();var curMonth = "" + (dgetMonth() + 1);var curDate = "" + dgetDate();var curHour = "" + dgetHours();var curMinute = "" + dgetMinutes();var curSecond = "" + dgetSeconds();if (curMonthlength == 1) {curMonth = "0" + curMonth;}if (curDatelength == 1) {curDate = "0" + curDate;}if (curHourlength == 1) {curHour = "0" + curHour;}if (curMinutelength == 1) {curMinute = "0" + curMinute;}if (curSecondlength == 1) {curSecond = "0" + curSecond;}var fileName = "leo_zhang" + "_" + curYear + curMonth + curDate + "_"+ curHour + curMinute + curSecond + "csv";//alert(fileName);return fileName;}function doFileExport(inName, inStr) {var xlsWin = null;if (!!documentall("glbHideFrm")) {xlsWin = glbHideFrm;}else {var width = 6;var height = 4;var openPara = "left=" + (windowscreenwidth / 2 - width / 2)+ ",top=" + (windowscreenheight / 2 - height / 2)+ ",scrollbars=no,width=" + width + ",height=" + height;xlsWin = windowopen("", "_blank", openPara);}xlsWindocumentwrite(inStr);xlsWindocumentclose();xlsWindocumentexecCommand('Saveas', true, inName);xlsWinclose();}

var tableRes = [];//导出的excelexcel表格字符串

var bodyList = [];//主体

var num = 1;//序号

var excelHead = [];//excel表头

var resData = [];//接口返回的列表

resDatamap( (item,index)=>{

let tableRow = []

let count = num++;

let obj = {}

obj["numberList"]= count;//序号

obj["factorycode"] = itemfactorycode;//车间编号

obj["equipmentcode"]= itemequipmentcode;//设备编号

obj["status"]= itemstatus;//状态

})

tableResunshift(excelHead);//添加表头

excelHead =[];//清空表头

=========================================================

function sheet2blob(sheet, sheetName) {

sheetName = sheetName || 'sheet1';

var workbook = {

SheetNames: [sheetName],

Sheets: {}

};

workbookSheets[sheetName] = sheet;

// 生成excel的配置项

var wopts = {

bookType: 'xlsx', // 要生成的文件类

bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性

type: 'binary'

};

var wbout = XLSXwrite(workbook, wopts);

var blob = new Blob([s2ab(wbout)], {type:"application/octet-stream"});

// 字符串转ArrayBuffer

function s2ab(s) {

var buf = new ArrayBuffer(slength);

var view = new Uint8Array(buf);

for (var i=0; i!=slength; ++i) view[i] = scharCodeAt(i) & 0xFF;

return buf;

}

return blob;

}

function openDownloadDialog(url, saveName){

if(typeof url == 'object' && url instanceof Blob){

url = URLcreateObjectURL(url); // 创建blob地址

}

var aLink = documentcreateElement('a');

aLinkhref = url;

aLinkdownload = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效

var event;

if(windowMouseEvent) event = new MouseEvent('click');

else{

event = documentcreateEvent('MouseEvents');

eventinitMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

}

aLinkdispatchEvent(event);

}

function exportExcel(tableInfo){

// var tableInfo = [

// ['主要信息', null, null, '其它信息'], // 特别注意合并的地方后面预留2个null

// ['姓名', '性别', '年龄', '注册时间'],

// ['张三', '男', 18, new Date()],

// ['李四', '女', 22, new Date()]

// ]

// tableInfo = ""

var sheet = XLSXutilsaoa_to_sheet(tableInfo);

sheet["!cols"] = [

{ wch: 8 },//宽度

{ wch: 15 },

{ wch: 15 },

{ wch: 15 },

{ wch: 15 },

{ wch: 15 },

{ wch: 15 },

{ wch: 15 },

{ wch: 20 },

{ wch: 20 },

];

// sheet['!merges'] = [

// // 设置A1-C1的单元格合并

// {s: {r: 0, c: 0}, e: {r: 0, c: 2}}

// ];

openDownloadDialog(sheet2blob(sheet), '车间订单列表xlsx');

}

exportExcel(tableRes);

以上就是关于js如何导出exel文件全部的内容,包括:js如何导出exel文件、怎么用JS获取到style标签里的内容、如何在多个sheet页里搜索spreadjs等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/10103278.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-05
下一篇 2023-05-05

发表评论

登录后才能评论

评论列表(0条)

保存