MemoryStream不从数据表写入数据

时间:2018-09-12 08:15:47

标签: c# excel memorystream xssf

我有一个要填充数据的数据表,然后传递给应该将数据写入内存流并将其另存为Excel电子表格的方法。数据表已正确填充,但是当内存流写入数据表时,内存流的容量为0。就好像它什么都没写一样。这可能是由于某种内存泄漏引起的吗?以下是我使用内存流编写工作簿(由数据表填充)的代码

    public static MemoryStream Grid_Export_Excel(DataTable data)
    {
        try
        {
            var workbook = new XSSFWorkbook();
            var sheet = workbook.CreateSheet();
            var headerRow = sheet.CreateRow(0);

            // Set the column names in the header row
            for (int i = 0; i < data.Columns.Count; i++)
                headerRow.CreateCell(i).SetCellValue(data.Columns[i].ColumnName);

            // Freeze the header row so that it's not scrolled
            sheet.CreateFreezePane(0, 1, 0, 1);

            for (int r = 0; r < data.Rows.Count; r++)
            {
                // Create a new row
                var row = sheet.CreateRow(r + 1);

                // Get the DataRow
                var dataRow = data.Rows[r];

                for (int c = 0; c < data.Columns.Count; c++)
                {
                    // Get the fieldname
                    var fieldname = data.Columns[c].ColumnName;

                    // Make sure that the field exists in the datarow
                    if (!dataRow.Table.Columns.Contains(fieldname))
                        continue;

                    // Create the cell in the row
                    row.CreateCell(c).SetCellValue(dataRow[fieldname].ToString());
                }
            }

            // Write the workbook to a stream and return as FileStreamResult
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            return ms;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

0 个答案:

没有答案