微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

需要帮助使用 .Net Framework 4.8/Webform 中的 NPOI 创建 Excel 电子表格

如何解决需要帮助使用 .Net Framework 4.8/Webform 中的 NPOI 创建 Excel 电子表格

抱歉长篇大论,但这是我的第一篇文章,我不知道我的金发姑娘的详细程度,要么太多要么太少。

我正在使用 .Net Framework 4.8:Webforms 在内部站点上工作,并尝试使用从 Oracle 视图中提取的数据创建 Excel 电子表格。

我正在使用 NPOI (https://github.com/nissl-lab/npoi) 来尝试完成此导出。我能够使用相同的库将电子表格导入 Oracle,因此希望我在导出时也能取得同样的成功。到目前为止,没有快乐。

这是现在发生的事情...

我的方法成功拉取了我需要的记录,NPOI创建了工作表、标题行、单元格,数据填充到了工作表对象中——我可以在调试器中看到数据。然后我尝试将工作表加载到 MemoryStream 中,然后尝试将 MemoryStream 作为电子表格附件返回。我的期望是我会看到浏览器的(边缘)另存为对话框出现,让我保存电子表格。相反,该方法结束,什么也没有——没有对话框,没有浏览器错误,调试器没有错误

这是三天努力完成这项任务的结果。 Google 已带我访问了许多站点 - 太多了,以至于我真的不记得过去几天我尝试过的所有步骤。似乎 Google 推荐的大多数网站都是针对 .Net Core 的,甚至更多是针对 MVC 的。当然,我已经搜索了 SO,但这里也没有快乐。我已经碰壁了,我终于注册了 SO。

这是我的方法。您可能会猜到,我有一个 asp:Button 调用方法,该方法页面代码隐藏的一部分:

protected void ExportHRAppToExcel_btn_Click(object sender,EventArgs e)
{

    try
    {
        string sql = @"select id,name,desc from list_select";

        ConnectionHrTrack conn = new ConnectionHrTrack();
        OracleDataAdapter da = new OracleDataAdapter(sql,conn.open());

        DataTable dt = new DataTable();

        da.Fill(dt);

        da.dispose();
        conn.Close();
        
        // filling in the workbook was adapted from
        // https://www.c-sharpcorner.com/blogs/export-to-excel-using-npoi-dll-library

        var properties = new[] { "id","name","desc" };
        var headers = new[] { "ID","Name","Application Description" };

        IWorkbook workbook;
        workbook = new XSSFWorkbook();
        ISheet sheet = workbook.CreateSheet("APPS");

        // create/fill header row  
        IRow row1 = sheet.CreateRow(0);

        for (int j = 0; j < dt.Columns.Count; j++)
        {
            ICell cell = row1.CreateCell(j);
            String columnName = dt.Columns[j].ToString();
            cell.SetCellValue(columnName);
        }

        // create/fill data rows  
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            IRow row = sheet.CreateRow(i + 1);
            for (int j = 0; j < dt.Columns.Count; j++)
            {

                ICell cell = row.CreateCell(j);
                String columnName = dt.Columns[j].ToString();
                cell.SetCellValue(dt.Rows[i][columnName].ToString());
            }
        }

        using (MemoryStream exportData = new MemoryStream())
        {
            Response.Clear();
            workbook.Write(exportData);
            
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            response.addheader("Content-disposition",string.Format("attachment;filename={0}","hr_apps.xlsx"));
            
            Response.BinaryWrite(exportData.ToArray());

            // in lieu of Response.End(),which is said to kill the memorystream and did return exceptions,// used the following.  Found the same three lines in different forums,one of which was:
            // https://stackoverflow.com/questions/20988445/how-to-avoid-response-end-thread-was-being-aborted-exception-during-the-exce
            Response.Flush(); // Sends all currently buffered output to the client.
            Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
            HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
        }

    }
    catch (Exception ex)
    {
        // here so i can see the exception when debugging in VS since the above returns *nothing* to the browser
        Console.WriteLine(ex.Message);
    }
}

我看过足够多的帖子,知道 NPOI 将创建一个可下载的电子表格。所以,显然错误在我这边,但我一直没能找到它。也许我的方法中的代码很好,但我尝试使用它的方式不是。唉,我还没有看到任何方法使用的例子,只是其中的代码示例。

任何建议都将不胜感激 - 特别是如果他们帮助我克服这堵沮丧之墙。

编辑:我忘了提及,Chrome 在操作结束时报告以下内容

资源被解释为 Document 但使用 MIME 类型 application/octet-stream 传输:“{localhost URL/page}”。

我的 Google 搜索都没有产生任何接近有用的结果。

** 已解决 **

显然文件已经被创建。出于某种原因,Edge 从未通知我询问是否要保存/打开。相反,它一直将文件保存在 AppData Local 的 MicrosoftEdgeDownloads 文件夹中,并且地这样做。我不知道为什么我没有收到通知,因为我已将其设置为通知我。

在我的辩护中,我很少使用 Edge。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。