question

Marvelocity-9381 avatar image
0 Votes"
Marvelocity-9381 asked cooldadtx answered

WebAPI Core v5.0 Export to Word and Excel trying to use Grid and return File

Hi,

I am writing a webAPI Core that export data to word and excel. I got two questions that I hope someone can help me.

In my Export To Word,

The old code is using System.Web.UI.WebControls.GridView to draw gridview from the UI table control.

In core, the GridView() is throwing and error and does not exist in the core libraries.

Is there an core equivalent?

In the export to Excel, I am getting an error when returning the following File object

return File(stream, "application/octet-stream", "MyFile - " + DateTime.now.ToString() + ".xlsx");


I get an error On File that it does not exist on this current context.

I tried the System.IO.File but that is not the correct namespace.



Any help is appreciated. Thanks

dotnet-aspnet-core-webapi
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

cooldadtx avatar image
0 Votes"
cooldadtx answered

I would never recommend that you export a control like GridView to anything. GridView is a UI element, not data and your exported document should be the data. But that is just my strong personal opinion. To me this is always the start of where things go wrong.

In regards to GridVew, that is a web forms control and not available in MVC or web API. Web API, technically, shouldn't have any UI elements including MVC in my view of the world.

The correct approach, to me, is to simply create the table you want in Word directly. It does mean it is possible that the HTML view differs from the document view but in many cases that is OK because one should be responsive and one is stuck to page size.

An alternative approach is to create a local RDL that is formatted the way you want. Then when you need to export run the report and have it export to the appropriate format. This provides the cleanest approach and allows you to customize the report to fit the requirements of the page. It also means that you can reuse the data you're already using for the UI.

For the File question, you're looking for the File method on Controller. That is already defined on base and is accessible directly from the controller as documented here. If it isn't finding it then I'd wager you aren't in the controller itself. The specific overload accepts the file stream, the content type and the filename. Although note that you shouldn't really be using a string literal for content type. Use MediaTypeNames.Application.Octet instead.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.