下载修改后的Excel文件在React中。

huangapple go评论122阅读模式
英文:

Download modified excel file in react

问题

我正在开发REACT JavaScript和Java应用程序。

在一个React页面上,单击按钮(React按钮),它应该处理数据,追加到Excel(Java中),然后下载到本地计算机上。

在React中,我尝试过:

  1. <Link
  2. to="/files/DataList.xlsx"
  3. target="_blank"
  4. download
  5. className="limited-anchor text-muted small"
  6. >
  7. Download Template
  8. </Link>

但在这里,我需要提供下载数据的路径(我不能硬编码路径以满足我的要求)。

从Java方面看:

  1. JSONArray jsArray = new JSONArray(productData);
  2. File file = new File("C:\\Users\\ME\\Downloads\\OutputData.csv");
  3. String csv = CDL.toString(jsArray);
  4. 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:

  1. &lt;Link
  2. to=&quot;/files/DataList.xlsx&quot;
  3. target=&quot;_blank&quot;
  4. download
  5. className=&quot;limited-anchor text-muted small&quot;
  6. &gt;
  7. Download Template
  8. &lt;/Link&gt;

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:

  1. JSONArray jsArray = new JSONArray(productData);
  2. File file=new File(&quot;C:\\Users\\ME\\Downloads\\OutputData.csv&quot;);
  3. String csv = CDL.toString(jsArray);
  4. 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

这是使用以下方法成功的:

  1. download(){
  2. var re = this.state.ReportData; // 从Java API获取的带有标题和行数据的ArrayList
  3. var csvStrings = re.join("%0A");
  4. var a = document.createElement("a");
  5. a.href = "data:attachment/csv," + csvStrings;
  6. a.target = "_Blank";
  7. a.download = "Report.csv";
  8. document.body.appendChild(a);
  9. a.click();
  10. }
英文:

It worked with following approach:

  1. download(){
  2. var re = this.state.ReportData; // Arraylist fetched from java API with headers and row data
  3. var csvStrings = re.join(&quot;%0A&quot;);
  4. var a = document.createElement(&quot;a&quot;);
  5. a.href = &quot;data:attachment/csv,&quot; + csvStrings;
  6. a.target = &quot;_Blank&quot;;
  7. a.download = &quot;Report.csv&quot;;
  8. document.body.appendChild(a);
  9. a.click();
  10. }

huangapple
  • 本文由 发表于 2020年7月28日 18:40:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63132239.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定