Using ASP.NET web page, I am exporting some data to excel spreadsheet (XLSX). The code is running fine when I run it using Visual Studio (it is exporting a XLSX file with correct data), but the same code fails when deployed to Testing Server.
It is not throwing any error, it simply exports a blank XLSX file.
Note: While debugging in the test server, I found that the data is getting fetched and temp file is also getting created properly, but the data is not getting written to the temp file (the weird thing is it doesn't through any error).
Added later
After doing some more research, I have found that there is no issue with small record set (say 1000, 2000). But when tried with ~20K records, I get a blank file.
I have been burning myself for last 2 days, someone rescue me :) ...
Code
string templateFile = @"C:\Templates\ExportFile.xlsx";
string tempFileName = Path.Combine(@"C:\Temp\", Path.GetRandomFileName());
tempFileName = Path.ChangeExtension(tempFileName, ".xlsx");
File.Copy(templateFile, tempFileName);
List<Customer> customerList = FetchCustomers();
DataTable dataTableObj = new DataTable("Customers$");
dataTableObj.Columns.Add(new DataColumn("CustomerID"));
dataTableObj.Columns.Add(new DataColumn("FirstName"));
dataTableObj.Columns.Add(new DataColumn("LastName"));
dataTableObj.Columns.Add(new DataColumn("CreatedDate"));
foreach (Customer customerObj in customerList)
{
DataRow dataRowObj = dataTableObj.NewRow();
dataRowObj["CustomerID"] = customerObj.CustomerID;
dataRowObj["FirstName"] = customerObj.FirstName;
dataRowObj["LastName"] = customerObj.LastName;
dataRowObj["CreatedDate"] = customerObj.CreatedDate;
dataTableObj.Rows.Add(dataRowObj);
}
using (OleDbConnection oleDbConnectionObj = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + tempFileName + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;\""))
{
OleDbCommand insertCommand = new OleDbCommand();
insertCommand.Connection = oleDbConnectionObj;
insertCommand.CommandText = @"INSERT INTO [Customers$] ([CustomerID], [FirstName], [LastName], [CreatedDate]) VALUES (?, ?, ?, ?)";
insertCommand.Parameters.Add("CustomerID", OleDbType.Numeric, 0, "CustomerID");
insertCommand.Parameters.Add("FirstName", OleDbType.VarChar, 0, "FirstName");
insertCommand.Parameters.Add("LastName", OleDbType.VarChar, 0, "LastName");
insertCommand.Parameters.Add("CreatedDate", OleDbType.Date, 0, "CreatedDate");
DataSet dataSetObj = new DataSet();
dataSetObj.Tables.Add(dataTableObj);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
dataAdapter.InsertCommand = insertCommand;
dataAdapter.Update(dataSetObj, "Customers$");
}
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
Response.AddHeader("Content-Disposition", "attachment; filename=Customers.xlsx");
Response.WriteFile(tempFileName);
Response.Flush();
Response.End();