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

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

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:

              &lt;Link
                to=&quot;/files/DataList.xlsx&quot;
                target=&quot;_blank&quot;
                download
                className=&quot;limited-anchor text-muted small&quot;
              &gt;
                
                Download Template
              &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:

    JSONArray jsArray = new JSONArray(productData);
    File file=new File(&quot;C:\\Users\\ME\\Downloads\\OutputData.csv&quot;);
    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(&quot;%0A&quot;);
    var a = document.createElement(&quot;a&quot;);
    a.href = &quot;data:attachment/csv,&quot; + csvStrings;
    a.target = &quot;_Blank&quot;;
    a.download = &quot;Report.csv&quot;;
    document.body.appendChild(a);
    a.click();
}

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:

确定