简体   繁体   中英

C# OpenXML make Excel file downloadable

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ExcelReportsController : Controller
{

    private ExcelContext db = new ExcelContext();

    [Route("/ExportToExcel")]
    [HttpGet]
    public void ExportPersonsToExcel()
    {
        var sqlParameters = new List<SqlParameter>();
        sqlParameters.Add(new SqlParameter("@id", "1"));
        var persons = db.Database.SqlQuery<TestExcel>("SELECT * FROM persons(@id)", sqlParameters.ToArray()).ToArray();
        DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (typeof(DataTable)));
        using (SpreadsheetDocument document = SpreadsheetDocument.Create("TestNewData.xlsx", SpreadsheetDocumentType.Workbook))
        {
            WorkbookPart workbookPart = document.AddWorkbookPart();
            workbookPart.Workbook = new Workbook();

            WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
            var sheetData = new SheetData();
            worksheetPart.Worksheet = new Worksheet(sheetData);

            Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
            Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };

            sheets.Append(sheet);
            Row headerRow = new Row();
            List<String> columns = new List<string>();
            foreach (DataColumn column in table.Columns)
            {
                columns.Add(column.ColumnName);
                Cell cell = new Cell();
                cell.DataType = CellValues.String;
                cell.CellValue = new CellValue(column.ColumnName);
                headerRow.AppendChild(cell);
            }

            sheetData.AppendChild(headerRow);
            foreach (DataRow dsrow in table.Rows)
            {
                Row newRow = new Row();
                foreach (String col in columns)
                {
                    Cell cell = new Cell();
                    cell.DataType = CellValues.String;
                    cell.CellValue = new CellValue(dsrow[col].ToString());
                    newRow.AppendChild(cell);
                }

                sheetData.AppendChild(newRow);
            }
            workbookPart.Workbook.Save();
        }
    }
}
}

I have the following code, but when i ask for the excel file, nothing happens. I want it to download automatically when I enter that URL. Any solutions?

Maybe a stream? But how would I implement that? I'm pretty new using this library - so bear with me.

First, change the return type of your method to IActionResult

Then, after the using block, add this:

var stream = System.IO.File.Open("TestNewData.xlsx", FileMode.Open);
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

It creates a FileStream from your file, then returns a FileStreamResult . The long string is the MIME type for Microsoft Excel (OpenXML) . Note, FileStreamResult should automatically dispose the stream.

If you wish to provide a name for the downloaded file, you can use an overloaded version of File , so just pass a third argument (of type string), like this:

return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "CustomName.xlsx");

I found a solution.

We have to return a HttpResponseMessage. Then after the "using" block, we add the following code:

var path = "TestNewData.xlsx";
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType =
            new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        return result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM