英文:
Download modified excel file in react
问题
我正在开发REACT JavaScript和Java应用程序。
在一个React页面上,单击按钮(React按钮),它应该处理数据,追加到Excel(Java中),然后下载到本地计算机上。
在React中,我尝试过:
<Link
to="/files/DataList.xlsx"
target="_blank"
download
className="limited-anchor text-muted small"
>
Download Template
</Link>
但在这里,我需要提供下载数据的路径(我不能硬编码路径以满足我的要求)。
从Java方面看:
JSONArray jsArray = new JSONArray(productData);
File file = new File("C:\\Users\\ME\\Downloads\\OutputData.csv");
String csv = CDL.toString(jsArray);
FileUtils.writeStringToFile(file, csv);
这只是将数据存储在指定位置。
预期流程:单击React页面上的下载按钮,它应该自动创建文件并下载到Downloads文件夹中(Windows/MAC)。
是否有办法处理整个流程?
英文:
I am working on REACT JavaScript and Java application.
On a react page, onclick of a button (react), it should manipulate data, append in Excel (Java), and then download it on the local machine.
In React I tried:
<Link
to="/files/DataList.xlsx"
target="_blank"
download
className="limited-anchor text-muted small"
>
Download Template
</Link>
But here I need to give a path to download the data. (I can't not hardcode the path with my requirement)
From Java side:
JSONArray jsArray = new JSONArray(productData);
File file=new File("C:\\Users\\ME\\Downloads\\OutputData.csv");
String csv = CDL.toString(jsArray);
FileUtils.writeStringToFile(file, csv);
This just stores the data in the location.
Expected flow: Onclick of Download button on react page, it should create file and download automatically in Downloads (Windows/MAC).
Is there any way to handle this entire flow?
答案1
得分: 0
这是使用以下方法成功的:
download(){
var re = this.state.ReportData; // 从Java API获取的带有标题和行数据的ArrayList
var csvStrings = re.join("%0A");
var a = document.createElement("a");
a.href = "data:attachment/csv," + csvStrings;
a.target = "_Blank";
a.download = "Report.csv";
document.body.appendChild(a);
a.click();
}
英文:
It worked with following approach:
download(){
var re = this.state.ReportData; // Arraylist fetched from java API with headers and row data
var csvStrings = re.join("%0A");
var a = document.createElement("a");
a.href = "data:attachment/csv," + csvStrings;
a.target = "_Blank";
a.download = "Report.csv";
document.body.appendChild(a);
a.click();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论