I have asp.net MVC app in c# and I get query results(from Entity Framework) and I need to put the data in Excel sheet which user can download. So this is what I am trying to do and I want to know how to write each row of data into excel sheet? Any other approach I should take is welcome too.
var certs = CertificateService.ReadAllSentCertificates();
Application excel = new Application();
string filePath = "C:/ToDoList/SentStats_" + DateTime.Now.ToString() + ".xls";
Workbook mybook = excel.Workbooks.Add();
excel.Visible = true;
try
{
mybook.Activate();
Worksheet mysheet = mybook.Worksheets.Add();
foreach (var x in certs)
{
// How to write each row in excel??
}
//mybook.SaveAs(Filename: filepath);
mybook.Save();
}
catch (Exception ex)
{
}
finally
{
mybook.Close();
}
Don't use Office interop in a web application. MS Office was never designed to run on a server. If you want to build an Excel sheet you could use OpenXML on the server.
As an alternative you could return a view containing the results in a <table> and serve this view with the application/vnd.ms-excel Content-Type response header. You will have far less control over the formatting of the resulting sheet compared to using the OpenXML SDK which gives you full control.
Related
One aspect of an ASP.net core (6) MVC app I am working on needs to query an SQL View that already resides in an Azure SQL MI.
I need to be able to query this SQL View to be able to retrieve the data based on user input but with the following conditions.
I cannot use Entity Framework.
The connection has to be read only.
This has to be database first.
As of yet I do not have access to this View or any of the tables it draws from. However I am expected to have code ready to plug a connection string into.
Unfortunately any resources I have been able to find don't seem to apply to my specific conditions. So any advice in what direction or approach would work best would be appreciated.
Those are by no means "silly" conditions. You didn't specify the language or the database but I'll make assumptions
I cannot use Entity Framework
Just use standard ado.net
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ado-net-code-examples#sqlclient
(I know that Link only answers are frowned upon)
The connection has to be read only.
Ensure that the account you connect under is read only. In SQL Server this is achieved by making you a member of the db_datareader group. This is something that should be enforced by the DBA that gives you an account
This has to be database first.
That's not really relevant. Just use the linked sample code to read from the existing view.
Literal copy paste of code at the link above:
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"SELECT ProductID, UnitPrice, ProductName from dbo.products "
+ "WHERE UnitPrice > #pricePoint "
+ "ORDER BY UnitPrice DESC;";
// Specify the parameter value.
int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#pricePoint", paramValue);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",
reader[0], reader[1], reader[2]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
I am working on .Net MVC WebAPI .I have fetch the data from my local database in visual studio and stored into csv file at my local machine in C drive. Now I want to upload to my google drive what should i do next?
[HttpGet]
[Route("Get")]
public void ExportcontentCSV()
{
StringBuilder sb = new StringBuilder();
var get = db.Clients.ToList();
sb.AppendFormat("{0},{1},{2},{3}",
"id", "FirstName", "LastName", "DOB");
sb.Append("\r\n");
foreach (var all in get)
{
sb.AppendFormat(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\"",
all.id, all.FirstName, all.LastName, all.DOB));
sb.Append("\r\n");
}
StreamWriter File = new StreamWriter(#"C:\New folder\pqr.csv");
File.WriteLine(sb.ToString());
File.Close();
}
Use Google Drive API , more details here
I have a project ASP.NET Core 2.0 MVC running on IIS.
Want to Export some information from data grid to Excel and save it from web page to the desktop of current user.
string fileName = "SN-export-" + DateTime.Now + ".xlsx";
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
fileName = rgx.Replace(fileName, ".");
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fileName2 = Path.Combine(path, fileName);
FileInfo excelFile = new FileInfo(fileName2);
excel.SaveAs(excelFile);
This works perfect local at Visual Studio, but not after publishing at IIS.
Using simple path string path = #"C:\WINDOWS\TEMP"; It will save this export file at the server temp folder, but not current web page user.
How to get this?
ASP.NET MVC is framework for a web application. So you have fronted and backend parts. This code will executed on the server side of your application. Even if you use Razor pages, they also generated at the backend. So there are several ways to save data on the computer:
use js to iterate data and save it, but I'm not sure that saving to excel with js is easy;
send desired data to backend, save it to excel and then return to the client.
For a second way you can use next code:
[Route("api/[controller]")]
public class DownloadController : Controller {
//GET api/download/12345abc
[HttpGet("{id}"]
public async Task<IActionResult> Download(YourData data) {
Stream stream = await {{__get_stream_based_on_your_data__}}
if(stream == null)
return NotFound();
return File(stream, "application/octet-stream"); // returns a FileStreamResult
}
}
And because of security reasons you can save data only to downloads directory.
I developed a website using Asp.Net MVC and Edmx database and I published this website on azure and my database is also on azure and I've a functionality on website that uploads excel record into database and that excel sheet contain almost 18000 records every time I upload that sheet it throw Timeout error after some time so what should I do.
Initially I was not using any command Timeout but after doing some research I'm using this in constructor
public ProfessionalServicesEntities()
: base("name=ProfessionalServicesEntities")
{
this.Database.CommandTimeout = 10000;
//this.Database.CommandTimeout = 0; //I tried this too.
//((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 3600;
}
Here is the code of
function :-
public void SaveEquipments(IEnumerable<EquipSampleEntity> collection)
{
using (ProfessionalServicesEntities db = new ProfessionalServicesEntities())
{
string modelXml = XmlSerialization.ListToXml(collection.Where(x=>x.Type == Model).ToList());
string accessoryXml = XmlSerialization.ListToXml(collection.Where(x => x.Type == Accessory).ToList());
db.ImportEquipmentFile(modelXml, accessoryXml);
}
}
here is context file code for SP:-
public virtual int ImportEquipmentFile(string modelXml, string accessoryXml)
{
var modelXmlParameter = modelXml != null ?
new ObjectParameter("ModelXml", modelXml) :
new ObjectParameter("ModelXml", typeof(string));
var accessoryXmlParameter = accessoryXml != null ?
new ObjectParameter("AccessoryXml", accessoryXml) :
new ObjectParameter("AccessoryXml", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("ImportEquipmentFile", modelXmlParameter, accessoryXmlParameter);
}
You may be processing the excel on upload itself and processing it row by row. You have two options, one is to schedule a background job to pickup the upload file and insert it to DB and complete the request.
Next option is to read the whole file in one go and do a single bulk insert into the DB.
There are too many things that can cause this. In Azure App Service there is a Front-end which has a timeout of 240 seconds. If your application takes more time, then you might run into this. This could be one of the probable causes.
In order to understand what is happening. Enabled Web Server Logging and Failed Request Tracing.
See this for how to proceed further: https://learn.microsoft.com/en-us/azure/app-service-web/web-sites-enable-diagnostic-log
I have an ASP.NET MVC2 application in development and I am having problems rendering a .pdf file from our production server.
On my Visual Studio 2010 integrated development server everything works fine, but after I publish the application to the production server, it breaks. It does not throw any exceptions or errors of any kind, it simply does not show the file.
Here's my function for displaying the PDF document:
public static void PrintExt(byte[] FileToShow, String TempFileName,
String Extension)
{
String ReportPath = Path.GetTempFileName() + '.' + Extension;
BinaryWriter bwriter =
new BinaryWriter(System.IO.File.Open(ReportPath, FileMode.Create));
bwriter.Write(FileToShow);
bwriter.Close();
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = ReportPath;
p.StartInfo.UseShellExecute = true;
p.Start();
}
My production server is running Windows Server 2008 and IIS 7.
You cannot expect opening the default program associated with PDF file browsing on the server. Try returning the file into the response stream which will effectively open it on the client machine:
public ActionResult ShowPdf()
{
byte[] fileToShow = FetchPdfFile();
return File(fileToShow, "application/pdf", "report.pdf");
}
And now navigate to /somecontroller/showPdf. If you want the PDF opening inside the browser instead of showing the download dialog you may try adding the following to the controller action before returning:
Response.AddHeader("Content-Disposition", "attachment; filename=report.pdf");
i suggest you use ASP.NET MVC FileResult Class to display the PDF.
see http://msdn.microsoft.com/en-us/library/system.web.mvc.fileresult.aspx
your code open`s the PDF on the webserver.
Here's how I did it.
public ActionResult PrintPDF(byte[] FileToShow, String TempFileName, String Extension)
{
String ReportPath = Path.GetTempFileName() + '.' + Extension;
BinaryWriter bwriter = new BinaryWriter(System.IO.File.Open(ReportPath, FileMode.Create));
bwriter.Write(FileToShow);
bwriter.Close();
return base.File(FileToShow, "application/pdf");
}
Thank you all for your efforts. Solution I used is the most similar to the Darin's one (almost the same, but his is prettier :D), so I will accept his solution.
Vote up for all of you folks (both for answers and comments)
Thanks