我对GWT完全陌生,如果这是一个琐碎的问题,非常抱歉,但我找不到答案。我有这个已经起作用的功能,可以在其中导出为.xlsx一个表。没关系,它导出文件没有任何问题。这是使用此第三方工具:https://github.com/stephenliberty/excel-builder.js/
我的问题我想将文件另存为.csv,但无法转换此gwt版本的JSONObject( com.google.gwt.json.client.JSONObject.JSONObject())导入到csv中,如果它也可以在csv中导出,我找不到关于此excel-builder-js的任何有用的文档...这怎么可能?
...
JSONObject object = new JSONObject();
object.put("head", head);
object.put("cols", columns);
object.put("data", array);
exportXlsxFromTable(JsonUtils.safeEval(object.toString()), GWT.getModuleName(), name);
...
public static native void exportXlsxFromTable(JavaScriptObject originalData, String project, String name) /*-{
var uri = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,';
$wnd
.require(
[ project + '/excelbuilderjs/excel-builder', project + '/excelbuilderjs/Template/BasicReport' ],
function(EB, BR, downloader) {
var basicReport = new BR({
name : name
});
basicReport.setHeader([
{bold: false, text: name}, "", ""
]);
var head = originalData['head'];
for (var i=0;i<head.length;i++) {
for (var j=0;j<head[i].length;j++) {
head[i][j].metadata = { type: 'string' };
}
}
basicReport.setData(head.concat(originalData['data']));
basicReport.setColumns(originalData['cols']);
var data = EB.createFile(basicReport.prepare());
// window.location.href = uri + data;
$entry(@com.mycompany.gxt.framework.view.dom.DOMUtils::downloadFile(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)("myfile.xlsx", uri, data));
});
}-*/;
public static native void downloadFile(String filename, String uri, String base64) /*-{
var iframeDownloadFn = function(filename, uri, base64) {
var values = {
fn : 'b64d',
fname : filename,
fcont : uri + base64
};
try {
$wnd.document.body.removeChild($wnd.downloadIframe);
} catch (e) {
}
var iframe = $wnd.document.createElement("iframe");
$wnd.document.body.appendChild(iframe);
var iDoc = iframe.contentWindow.document;
var form = iDoc.createElement("form");
form
.setAttribute("action",
@com.mycompany.gxt.framework.client.FrameworkClient::DOWNLOAD_URL);
form.setAttribute("method", 'POST');
form.setAttribute("style", 'display: none');
for ( var property in values) {
if (values.hasOwnProperty(property)) {
var value = values[property];
if (value instanceof Array) {
for (var i = 0, l = value.length; i < l; i++) {
var el = iDoc.createElement("input");
el.setAttribute("type", 'hidden');
el.setAttribute("name", property);
el.setAttribute("value", value[i]);
form.appendChild(el);
}
} else {
var el1 = iDoc.createElement("input");
el1.setAttribute("type", 'hidden');
el1.setAttribute("name", property);
el1.setAttribute("value", value);
form.appendChild(el1);
}
}
}
iDoc.body.appendChild(form);
form.submit();
$wnd.downloadIframe = iframe;
}
var clickLink = function(link, uri, base64) {
var cancelled = true;
try {
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
event.initMouseEvent("click", true, true, window, 0, 0, 0,
0, 0, false, false, false, false, 0, null);
cancelled = !link.dispatchEvent(event);
} else if (link.fireEvent) {
cancelled = !link.fireEvent("onclick");
}
} catch (e) {
cancelled = true;
}
link.parentNode.removeChild(link);
if (cancelled) {
iframeDownloadFn(filename, uri, base64);
}
}
var link = $wnd.document.createElement("a");
link.setAttribute("href", uri + base64);
link.setAttribute("name", filename);
link.setAttribute("title", filename);
link.setAttribute("download", filename);
$wnd.document.body.appendChild(link);
clickLink(link, uri, base64);
}-*/;
编辑。
尝试了“ Mon Mohon Singha”中的javasript建议,我现在在这里:
JSONObject object = new JSONObject();
object.put("head", head);
object.put("cols", columns);
object.put("data", array);
exportCsvFromTable(object.toString(), GWT.getModuleName(), name);
public static native void exportCsvFromTable(String originalData, String project, String name) /*-{
var uri = 'text/csv;charset=utf-8;';
function convertToCSV(jsData){
var json = jsData;
var fields = Object.keys(json[0]);
var replacer = function(key, value) { return value === null ? '' : value }
var csv = json.map(function(row){
return fields.map(function(fieldName){
return JSON.stringify(row[fieldName], replacer)
}).join(',')
})
csv.unshift(fields.join(',')) // add header column
return csv.join('\r\n');
}
var data = convertToCSV(originalData);
// window.location.href = uri + data;
$entry(@com.mycompany.gxt.framework.view.dom.DOMUtils::downloadFile(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)("export.csv", uri, data));
}-*/;
但是我遇到这个错误,所以我假设我没有使用正确的类型...
com.google.gwt.logging.client.LogConfiguration
SEVERE: Exception caught: Exception caught: (TypeError) : json_0_g$.map is not a function com.google.gwt.event.shared.UmbrellaException: Exception caught: Exception caught: (TypeError) : json_0_g$.map is not a function
at Unknown.fillInStackTrace_0_g$(as-0.js@3:130944)
at Unknown.Throwable_3_g$(as-0.js@8:130899)
at Unknown.Exception_3_g$(as-0.js@18:131042)
at Unknown.RuntimeException_3_g$(as-0.js@18:287158)
at Unknown.UmbrellaException_3_g$(as-0.js@25:313985)
EDIT2。:
这是注销的JavaScriptObject。删除了一些“数据”行以使其更加清晰:
Object
cols: Array(10)
0: {name: "ID", type: "string"}
1: {name: "NAME", type: "string"}
2: {name: "FIRST NAME", type: "string"}
3: {name: "BIRTHDAY", type: "string"}
4: {name: "BIRTH PLACE", type: "string"}
5: {name: "BIRTH COUNTRY", type: "string"}
6: {name: "NATIONALITY", type: "string"}
7: {name: "ORGANISATION", type: "string"}
8: {name: "FUNCTION", type: "string"}
9: {name: "PLACE", type: "string"}
length: 10
__proto__: Array(0)
data: Array(100)
0: (10) [1470, "John", "Doe", "03.03.1988", "", "", "CANADA", "BPA", "", ""]
1: (10) [1469, "Test", "NAme", "25.03.1999", "CANADA", "CANADA", "CANADA", "test", "", "LA"]
2: (10) [1467, "Mike", "Test2", "06.05.2019", "Paris", "", "", "test", "ikol", "LA"]
3: (10) [1465, "Flanders", "Ned2", "23.12.1974", "Salt Lake City", "", "", "Orgatest", "BPA", ""]
4: (10) [1462, "Bro", "Jo", "03.07.2018", "abc", "USA", "USA", "MY COMPANY", "Catering", "A"]
5: (10) [1461, "Bro", "Jo", "01.08.2018", "abc", "USA", "USA", "MY COMPANY", "Catering", "A"]
...
length: 100
__proto__: Array(0)
head: Array(1)
0: (10) ["ID", "NAME", "FIRST NAME", "BIRTHDAY", "BIRTH PLACE", "BIRTH COUNTRY", "NATIONALITY", "ORGANISATION", "FUNCTION", "PLACE"]
length: 1
__proto__: Array(0)
__proto__: Object
EDIT3。:
正如罗布·牛顿(Rob Newton)所建议的那样,我这样编辑了convert函数:
public static native void exportCsvFromTable(JavaScriptObject originalData, String project, String name) /*-{
var uri = 'text/csv;charset=utf-8;';
function convertToCSV(jsData){
//console.log(originalData);
var json = jsData;
//var fields = Object.keys(json);
//var replacer = function(key, value) { return value === null ? '' : value }
var headerCSV = json.head[0].join(',');
var rowsCSV = json.data.map( function(row) {
return row.join(',');
} );
rowsCSV.unshift(headerCSV);
console.log(rowsCSV.join('\r\n'));
return rowsCSV.join('\r\n');
}
var data = convertToCSV(originalData);
// window.location.href = uri + data;
$entry(@com.mycompany.gxt.framework.view.dom.DOMUtils::downloadFile(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)("export.csv", uri, data));
}-*/;
转换后的数据看起来还可以:
ID,NAME,FIRST NAME,BIRTHDAY,BIRTH PLACE,BIRTH COUNTRY,NATIONALITY,ORGANISATION,FUNCTION,PLACE
31471,Test,Test,07.05.2019,New,,,XYZ,ikl,
31470,John,Doe,03.03.1988,,,Canada,XYZ,,
31469,New,Test,25.03.1999,Right,USA,USA,,LA
...
不幸的是,下载产生的文件无效,字节数为0:(
答案 0 :(得分:0)
将JSON数据转换为js中的csv
我不知道GWT。可能会对您有帮助
function convertToCSV(jsData){
var json = jsData;
var fields = Object.keys(json[0]);
var replacer = function(key, value) { return value === null ? '' : value }
var csv = json.map(function(row){
return fields.map(function(fieldName){
return JSON.stringify(row[fieldName], replacer)
}).join(',')
})
csv.unshift(fields.join(',')) // add header column
return csv.join('\r\n');
}
function exportCSVFile(items, fileTitle) {
var csv = convertToCSV(items);
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) {
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
return true
}
答案 1 :(得分:0)
您需要将JavaScriptObject传递给转换器函数,而不是包含JSON的字符串。尝试对代码进行以下更改:
exportCsvFromTable(object.getJavaScriptObject(), GWT.getModuleName(), name);
public static native void exportCsvFromTable(JavaScriptObject originalData, String project, String name) /*-{
您将显示对象具有名为head
的属性,该属性是长度为1的数组,而head [0]是标题行列名称的数组。因此,如下所示将为您提供标题行字符串:
var headerCSV = json.head[0].join(',');
实际的数据行位于名为data
的属性中,该属性是一个数组,并且数组中的每个项目都是该行中的值的数组。
var rowsCSV = json.data.map( function(row) {
return row.join(',');
} );
现在加入标题和行,例如:
rowsCSV.unshift(headerCSV) // add header column
return rowsCSV.join('\r\n');