Trying to get Filepath with Open Dialog - c#

I am currently making a web application using epPlus along with it to save the current database to an excel file. That part is easy and working, but what I'm trying to do is create a pop up dialog box that will allow the client to select the directory they want to save the excel file to. Then use the path they've given me and use the SaveAs function in epPlus with the path they have selected.
The question is how do I go about getting the dialog box to work and getting the path? I've tried using Response and I can't seem to get that working. The problem is that the excel file is only an object until save is done, and I need the path to do the save. Ideas? here's my code.
protected void OnbtnSaveExcelFileClick(object sender, EventArgs e)
{
String FileName = "GamingRecords";
String FilePath = #"C:\....\";
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
try
{
using (var package = new ExcelPackage(flUploadLink.FileContent))
{
var worksheet = package.Workbook.Worksheets.Add("Games to Date - " + DateTime.Now.ToShortDateString());
worksheet.DefaultRowHeight = 22;
var headers = new[] { Constants.GameTitle, Constants.GameGenre, Constants.Price, Constants.Quantity };
for (var i = 1; i < headers.Count() + 1; i++)
worksheet.Cells[1, i].Value = headers[i - 1];
var game = new GameClass();
var list = game.FetchAll();
var rowNumber = 2;
foreach (var t in list)
{
worksheet.Cells[rowNumber, 1].Value = t.GameTitle;
worksheet.Cells[rowNumber, 2].Value = t.GameGenre;
worksheet.Cells[rowNumber, 3].Value = t.Price;
worksheet.Cells[rowNumber, 4].Value = t.Quantity;
rowNumber++;
}
for (var i = 1; i < worksheet.Dimension.End.Column; i++)
worksheet.Column(i).AutoFit();
package.Workbook.Properties.Title = "Games on Record";
package.Workbook.Properties.Author = "Kirk Rudzinski";
package.Workbook.Properties.Company = "Logistics+";
package.Save();
litExcelError.Visible = false;
}
}
catch (IOException)
{ litExcelError.Text = "Please close the file to make modifications"; }
}

Alright, just to clarify I figured out how to do it the way I was trying. For reference in case anyone runs into an error like this here is the code!
protected void OnbtnSaveExcelFileClick(object sender, EventArgs e)
{
try
{
using (var package = new ExcelPackage(flUploadLink.FileContent))
{
var worksheet = package.Workbook.Worksheets.Add("Games to Date - " + DateTime.Now.ToShortDateString());
worksheet.DefaultRowHeight = 22;
var headers = new[] { Constants.GameTitle, Constants.GameGenre, Constants.Price, Constants.Quantity };
for (var i = 1; i < headers.Count() + 1; i++)
worksheet.Cells[1, i].Value = headers[i - 1];
int rowNumber = 2;
foreach (GridViewRow row in grdGamingTable.Rows)
{
var index = row.RowIndex;
worksheet.Cells[rowNumber, 1].Value = grdGamingTable.Rows[index].Cells[2].Text;
worksheet.Cells[rowNumber, 2].Value = grdGamingTable.Rows[index].Cells[3].Text;
worksheet.Cells[rowNumber, 3].Value = Convert.ToInt16(grdGamingTable.Rows[index].Cells[4].Text);
worksheet.Cells[rowNumber, 4].Value = Convert.ToInt16(grdGamingTable.Rows[index].Cells[5].Text);
rowNumber++;
}
for (var i = 1; i < worksheet.Dimension.End.Column; i++)
worksheet.Column(i).AutoFit();
package.Workbook.Properties.Title = "Games on Record";
package.Save();
litExcelError.Visible = false;
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=GameRecords.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
}
}
catch (IOException)
{ litExcelError.Text = "Please close the file to make modifications"; }
}

Related

Save data from datagridview to excel file

i have created function to save data from datagridview to excel file.
Function to save :
try
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Records";
try
{
for (int i = 0; i < dataGridView2.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dataGridView2.Columns[i].HeaderText;
}
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 0; j < dataGridView2.Columns.Count; j++)
{
if (dataGridView2.Rows[i].Cells[j].Value != null)
{
worksheet.Cells[i + 2, j + 1] = dataGridView2.Rows[i].Cells[j].Value.ToString();
}
else
{
worksheet.Cells[i + 2, j + 1] = "";
}
}
}
//Getting the location and file name of the excel to save from user.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show("Export Successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
app.Quit();
workbook = null;
worksheet = null;
}
}
catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
And it works good on my computer with version :
I try to run this on my second computer where is installed :
What i need to change in code to works with both versions?
I'm looking example that will do the same but works on every office installation.
Btw when i try to run on second computer i have this error :
This isn't an answer directly to why your code throws that error. But as an alternative approach that works for me, could be worth trying? I used 'ClosedXML' package from Nuget... There are probably other options out there too like 'yob's reply, that I'm sure would also work fine.
using ClosedXML.Excel;
Then to save data:
SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.Filter = "Excel file|*.xlsx";
saveFile1.Title = "save results as Excel spreadsheet";
saveFile1.FileName = title + " -" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
if (saveFile1.ShowDialog() == DialogResult.OK)
{
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add(data, title);
wb.SaveAs(saveFile1.FileName);
}
'data' is a datatable, so you would need to convert the datagridview to datatable first. As I said, not an answer to your existing code, but a possible alternative that works for me :) Good luck.
if you're not bound to use MS Office components, then I'd suggest to use EPPlus library instead.
string saveasFileName = .....
using (var package = new ExcelPackage())
{
using (var worksheet = package.Workbook.Worksheets.Add("Records"))
{
worksheet.Cells[1, 1].Value = "Records from dataGridView2:";
worksheet.Cells[1, 1].Style.Font.Bold = true;
// column headers
for (int i = 0; i < dataGridView2.Columns.Count; i++)
{
worksheet.Cells[2, i + 1].Value = dataGridView2.Columns[i].HeaderText;
}
// actual data
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 0; j < dataGridView2.Columns.Count; j++)
{
// ... populate worksheet ...
worksheet.Cells[i + 3, j + 1].Value = dataGridView2.Rows[i].Cells[j].Value?.ToString()??"";
}
}
// save
package.SaveAs(saveasFileName);
}
}
I have an example at https://github.com/siccolo/EppPlus_CreateExcel/blob/master/Excel.cs
#Adamszsz - if you need to open an excel file and load into gridview, then you can use oledb connection, for example: - open excel file .xls:
...
var excelconnection = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
var table = "[Sheet1$]"
// using System.Data.OleDb
var excel = new OleDbDataAdapter("SELECT * FROM " + table, excelconnection);
var exceldata = new DataTable();
excel.Fill(exceldata);
...
while for excel file .xlsx use Net.SourceForge.Koogra.Excel2007.

Add Company logo in top of the excel

Need to add logo in the top of the excel file while downloading.
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ClearContent();
Response.ClearHeaders();
string FileName = "MachinePlanning" + DateTime.Now + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
GridView1.GridLines = GridLines.Both;
GridView1.HeaderStyle.Font.Bold = true;
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
You need to do it by Open XML or NPOI.Dll.
Below code will export excel with the company logo. but you need to add NPOI.DLL.
public static MemoryStream ExportToExcelWithCompanyLogo(DataTable dt, string sheetName, string CompanyLogo,Dictionary<string, string> filters)
{
//Create new Excel Workbook
var workbook = new HSSFWorkbook();
//Create new Excel Sheet
var sheet = workbook.CreateSheet(sheetName);
// Add Image Section
var patriarch = sheet.CreateDrawingPatriarch();
HSSFClientAnchor anchor;
anchor = new HSSFClientAnchor(0, 0, 0, 0, (short)1, 1, (short)5, 6);
anchor.AnchorType = 2;
string imagesPath = CompanyLogo;
//grab the image file
//imagesPath = System.IO.Path.Combine(imageLocation, "image.jpg");
//create an image from the path
System.Drawing.Image image = System.Drawing.Image.FromFile(imagesPath);
MemoryStream ims = new MemoryStream();
//pull the memory stream from the image (I need this for the byte array later)
image.Save(ims, System.Drawing.Imaging.ImageFormat.Jpeg);
int index = workbook.AddPicture(ims.ToArray(), PictureType.JPEG);
var picture = patriarch.CreatePicture(anchor, index);
picture.Resize(0.8);
//picture.LineStyle = HSSFPicture.LINESTYLE_DASHDOTGEL;
sheet.ForceFormulaRecalculation = true;
// End of Add image
// font Style for Excel title
HSSFFont hFont = (HSSFFont)workbook.CreateFont();
hFont.FontHeightInPoints = 16;
hFont.FontName = "Calibri";
hFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
HSSFCellStyle hStyle = (HSSFCellStyle)workbook.CreateCellStyle();
hStyle.Alignment = HorizontalAlignment.Center;
hStyle.VerticalAlignment = VerticalAlignment.Top;
hStyle.SetFont(hFont);
// end of excel title style
// font for Table header Stylr
HSSFFont thhFont = (HSSFFont)workbook.CreateFont();
thhFont.FontHeightInPoints = 12;
thhFont.FontName = "Calibri";
thhFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
HSSFCellStyle thhStyle = (HSSFCellStyle)workbook.CreateCellStyle();
thhStyle.Alignment = HorizontalAlignment.Left;
thhStyle.VerticalAlignment = VerticalAlignment.Top;
thhStyle.SetFont(thhFont);
// end of table header font
var cra = new NPOI.SS.Util.CellRangeAddress(6, 7, 4, 9);
sheet.AddMergedRegion(cra);
// Add filters to sheet
int filterRows = 9;
foreach (var key in filters)
{
var FilterRow = sheet.CreateRow(filterRows);
FilterRow.CreateCell(4).SetCellValue(key.Key + " : ");
FilterRow.CreateCell(5).SetCellValue(key.Value);
filterRows++;
}
var HeaderRowNumber = 9 + filters.Keys.Count + 1;
//Add rows
var headerRow = sheet.CreateRow(HeaderRowNumber);
//int totalcolumns = dt.Columns.Count;
int columncounter = 0;
if (dt.Rows.Count > 0)
{
foreach (DataColumn c in dt.Columns)
{
var cell = headerRow.CreateCell(columncounter + 1);
cell.SetCellValue(c.ColumnName);
cell.CellStyle = thhStyle;
columncounter++;
}
//(Optional) freeze the header row so it is not scrolled
//sheet.CreateFreezePane(0, 1, 0, 1);
int rowNumber = HeaderRowNumber + 1;
int dtrowNumber = 1;
//Populate the sheet with values from the grid data
foreach (var rows in dt.Rows)
{
//Create a new Row
var row = sheet.CreateRow(rowNumber);
//Set cell Value
for (int cellnumber = 0; cellnumber < columncounter; cellnumber++)
row.CreateCell(cellnumber + 1).SetCellValue(dt.Rows[dtrowNumber - 1][cellnumber].ToString());
rowNumber++;
dtrowNumber++;
}
// create 2 blank rows
for (int i = 0; i < 2; i++)
{
//Create a new Row
var row = sheet.CreateRow(rowNumber);
//Set cell Value
for (int cellnumber = 0; cellnumber < columncounter; cellnumber++)
row.CreateCell(cellnumber + 1).SetCellValue("");
rowNumber++;
}
// Add Date of extraction and source
var extractedDate = sheet.CreateRow(rowNumber);
var ecel = extractedDate.CreateCell(4);
ecel.SetCellValue("Extracted Date : ");
// ecel.CellStyle = hStyle;
extractedDate.CreateCell(5).SetCellValue(DateTime.Now.ToString("dd - MMM - yyyy"));
rowNumber++;
var Disclaimer = sheet.CreateRow(rowNumber);
var dcel = Disclaimer.CreateCell(4);
dcel.SetCellValue("Disclaimer : ");
// dcel.CellStyle = hStyle;
Disclaimer.CreateCell(5).SetCellValue("All Rights Reserved.");
rowNumber++;
var Disclaimer1 = sheet.CreateRow(rowNumber);
Disclaimer1.CreateCell(5).SetCellValue("Give some information at footer");
rowNumber++;
}
else
{
for (int i = 0; i <= 10; i++)
headerRow.CreateCell(i).SetCellValue("");
}
// End of add rows
//Write the Workbook to a memory stream
MemoryStream output = new MemoryStream();
workbook.Write(output);
return output;
}
you can download NPOI.Dll from this link
Download NPOI.dll
Hope this will solve your problem.

Trouble while Exporting GridView Data in Excel C#

Having trouble while exporting the gridview data in excel. It is exporting the whole page not Gridview data.
My Code as below :
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmlwritter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/ms-excel";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", "DSR"+DateTime.Now.ToString("dd-MM-yyyy")+".xls"));
GridView1.GridLines = GridLines.Both;
GridView1.HeaderStyle.Font.Bold = true;
GridView1.RenderControl(htmlwritter);
Response.Write(strwritter.ToString());
Response.End();
You can try doing something like that. Simple and straightforward.
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmlwritter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmlwritter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/ms-excel";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", "DSR"+DateTime.Now.ToString("dd-MM-yyyy")+".xls"));
GridView1.RenderBeginTag(htmlwritter);
GridView1.HeaderRow.RenderControl(htmlwritter);
foreach (GridViewRow row in GridView1.Rows)
{
row.RenderControl(htmlwritter);
}
GridView1.FooterRow.RenderControl(htmlwritter);
GridView1.RenderEndTag(htmlwritter);
Response.Write(strwritter.ToString());
Response.End();
A simple solution to this problem is to get your C# code to write the GridView's data source to an Excel file.
Here's the C# library I wrote to do exactly that:
Export to Excel
All source code is provided free of charge, and you just need to add a few lines to your ASP.Net code:
// The following ASP.Net code gets run when I click on my "Export to Excel" button.
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
// It doesn't get much easier than this...
CreateExcelFile.CreateExcelDocument(listOfEmployees, "Employees.xlsx", Response);
}
The other advantage of this is that it'll create a "real" .xlsx file (using the OpenDocument library). The downside is that those Microsoft libraries weigh-in at about 5Mb.
Try this,it will work..
private void Export_To_Excel()
{
Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
try
{
worksheet = workbook.ActiveSheet;
worksheet.Name = "ExportedFromDatGrid";
int cellRowIndex = 1;
int cellColumnIndex = 1;
////Loop through each row and read value from each column.
for (int i = 0; i < this.dGV.Rows.Count - 1; i++)
{
for (int j = 0; j < this.dGV.Columns.Count; j++)
{
//// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
if (cellRowIndex == 1)
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = this.dGV.Columns[j].HeaderText;
worksheet.Cells[cellRowIndex, cellColumnIndex].Font.FontStyle = FontStyle.Bold;
}
else
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = this.dGV.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}
worksheet.Columns.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
worksheet.Columns.AutoFit();
////Getting the location and file name of the excel to save from user.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx";
saveDialog.FilterIndex = 2;
if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show("Export Successful", "Info", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
}
finally
{
excel.Quit();
workbook = null;
excel = null;
}
}
Here an example that uses EPPlus. Just input a SQL query (or stored procedure name) and a filename to exportToExcel and you'll get an Excel file.
exportToExcel("SELECT * FROM yourTable", "myFileName");
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Globalization;
using System.Web;
//=== create an excel document =========================================
public static void exportToExcel(string sqlQuery, string fileName)
{
HttpResponse Response = HttpContext.Current.Response;
DataTable dt = loadExternalDataTable(sqlQuery);
using (ExcelPackage p = new ExcelPackage())
{
//create a new workbook
p.Workbook.Properties.Author = "VDWWD";
p.Workbook.Properties.Title = fileName;
p.Workbook.Properties.Created = DateTime.Now;
//create a new worksheet
p.Workbook.Worksheets.Add(fileName);
ExcelWorksheet ws = p.Workbook.Worksheets[1];
ws.Name = fileName;
ws.Cells.Style.Font.Size = 11;
ws.Cells.Style.Font.Name = "Calibri";
createExcelHeader(ws, dt);
createExcelData(ws, dt);
ws.Cells[ws.Dimension.Address].AutoFitColumns();
//make all columms just a bit wider, they would sometimes not fit
for (int col = 1; col <= ws.Dimension.End.Column; col++)
{
ws.Column(col).Width = ws.Column(col).Width + 1;
}
//send the file to the browser
byte[] bin = p.GetAsByteArray();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-length", bin.Length.ToString());
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".xlsx\"");
Response.OutputStream.Write(bin, 0, bin.Length);
Response.Flush();
Response.Close();
Response.End();
}
}
//=== create the excel sheet header row =========================================
private static void createExcelHeader(ExcelWorksheet ws, DataTable dt)
{
int colindex = 1;
//loop all the columns
foreach (DataColumn dc in dt.Columns)
{
var cell = ws.Cells[1, colindex];
//make the text bold
cell.Style.Font.Bold = true;
//make the background of the cell gray
var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#BFBFBF"));
//fill the cell with the text
cell.Value = dc.ColumnName.ToUpper();
colindex++;
}
}
//=== create the excel sheet data =========================================
private static void createExcelData(ExcelWorksheet ws, DataTable dt)
{
int colindex = 0;
int rowindex = 1;
//loop all the rows
foreach (DataRow dr in dt.Rows)
{
colindex = 1;
rowindex++;
//loop all the columns
foreach (DataColumn dc in dt.Columns)
{
var cell = ws.Cells[rowindex, colindex];
string datatype = dc.DataType.ToString();
//fill the cell with the data in the correct format, needs to be done here because the headder row makes every column a string otherwise
if (datatype == "System.Decimal" || datatype == "System.Double" || datatype == "System.Float")
{
if (!string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
cell.Value = Convert.ToDecimal(dr[dc.ColumnName]);
cell.Style.Numberformat.Format = "0.00";
}
else if (datatype == "System.Int16" || datatype == "System.Int32" || datatype == "System.Int64" || datatype == "System.Long")
{
if (!string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
cell.Value = Convert.ToInt64(dr[dc.ColumnName]);
}
else if (datatype == "System.Bool" || datatype == "System.Boolean")
{
if (!string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
cell.Value = Convert.ToBoolean(dr[dc.ColumnName]); ;
}
else if (datatype == "System.DateTime")
{
if (!string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
cell.Value = Convert.ToDateTime(dr[dc.ColumnName]);
cell.Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
}
else
{
cell.Value = dr[dc.ColumnName];
}
colindex++;
}
}
}
//=== create a datatable from a query =========================================
public static DataTable loadExternalDataTable(string sqlQuery)
{
DataTable dt = new DataTable();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString()))
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlQuery, connection))
{
try
{
adapter.Fill(dt);
}
catch
{
}
}
return dt;
}
This code may be help you
protected void btnExportExcel_Click(object sender, EventArgs e)
{
BindData();
GridView1.Visible = true;
string FileName = "Deal Report_(" + DateTime.Now.AddHours(5).ToString("yyyy-MM-dd") + ").xls";
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=" + FileName);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.HeaderRow.Style.Add("color", "#FFFFFF");
GridView1.HeaderRow.Style.Add("background-color", "#1F437D");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
row.BackColor = System.Drawing.Color.White;
row.Attributes.Add("class", "textmode");
if (i % 2 != 0)
{
for (int j = 0; j < row.Cells.Count; j++)
{
//row.Cells[j].Style.Add("background-color", "#eff3f8");
}
}
}
GridView1.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
GridView1.Visible = false;
}

Downloading Excel file after creating using EPPlus

I am using the EPPlus library to generate an excel file which I successfully save in a folder on the server.
How can download this file to my local machine?
This is my code
public void CreateExcelFirstTemplate()
{
var fileName = "C:\ExcelDataTest\ExcellData.xlsx";
var file = new FileInfo(fileName);
using (var package = new OfficeOpenXml.ExcelPackage(file))
{
var worksheet = package.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Attempts");
worksheet = package.Workbook.Worksheets.Add("Assessment Attempts");
worksheet.Row(1).Height = 20;
worksheet.TabColor = Color.Gold;
worksheet.DefaultRowHeight = 12;
worksheet.Row(1).Height = 20;
worksheet.Cells[1, 1].Value = "Employee Number";
worksheet.Cells[1, 2].Value = "Course Code";
var cells = worksheet.Cells["A1:J1"];
var rowCounter = 2;
foreach (var v in userAssessmentsData)
{
worksheet.Cells[rowCounter, 1].Value = v.CompanyNumber;
worksheet.Cells[rowCounter, 2].Value = v.CourseCode;
rowCounter++;
}
worksheet.Column(1).AutoFit();
worksheet.Column(2).AutoFit();
package.Workbook.Properties.Title = "Attempts";
package.Save();
}
}
If you are generating this file on each request you don't need to save it on the server:
public void CreateExcelFirstTemplate()
{
var fileName = "ExcellData.xlsx";
using (var package = new OfficeOpenXml.ExcelPackage(fileName))
{
var worksheet = package.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Attempts");
worksheet = package.Workbook.Worksheets.Add("Assessment Attempts");
worksheet.Row(1).Height = 20;
worksheet.TabColor = Color.Gold;
worksheet.DefaultRowHeight = 12;
worksheet.Row(1).Height = 20;
worksheet.Cells[1, 1].Value = "Employee Number";
worksheet.Cells[1, 2].Value = "Course Code";
var cells = worksheet.Cells["A1:J1"];
var rowCounter = 2;
foreach (var v in userAssessmentsData)
{
worksheet.Cells[rowCounter, 1].Value = v.CompanyNumber;
worksheet.Cells[rowCounter, 2].Value = v.CourseCode;
rowCounter++;
}
worksheet.Column(1).AutoFit();
worksheet.Column(2).AutoFit();
package.Workbook.Properties.Title = "Attempts";
this.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
this.Response.AddHeader(
"content-disposition",
string.Format("attachment; filename={0}", "ExcellData.xlsx"));
this.Response.BinaryWrite(package.GetAsByteArray());
}
}
Instead of using package.Save() you can use package.GetAsByteArray() which will return a byte array which you can then stream using FileResult or FileContentResult from the MVC action to trigger a file download. This method will allow you to download the file without saving it to the server first.
Here is sample action to download file. Feel free to modify it as per your requirement.
public FileActionResult DownloadMyFile()
{
var filePath = "C:\ExcelDataTest\ExcellData.xlsx";
var fileName = "ExcellData.xlsx";
var mimeType = "application/vnd.ms-excel";
return File(new FileStream(filePath, FileMode.Open),mimeType, fileName);
}
You can do like this:
excel.Workbook.Properties.Title = "Attempts";
this.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
this.Response.AddHeader("content-disposition",string.Format("attachment; filename={0}", "ExcellData.xlsx"));
this.Response.BinaryWrite(excel.GetAsByteArray());
For detailed blog: http://sforsuresh.in/generating-and-formatting-excelsheet-in-c-using-epplus/

Unable to generate the .xlsx file

I have a text file which is in tab deliminator and following is my code to generate its Excel.
protected void to_excel(object sender, EventArgs e)
{
string filepath = Path.Combine(Server.MapPath("~/Files"), fileupload.FileName);
fileupload.SaveAs(filepath);
string fname = fileupload.PostedFile.FileName;
DataTable dt = (DataTable)ReadToEnd(filepath);
string sFilename = fname.Substring(0, fname.IndexOf("."));
HttpResponse response = HttpContext.Current.Response;
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + sFilename + ".xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
private object ReadToEnd(string filePath)
{
DataTable dtDataSource = new DataTable();
string[] fileContent = File.ReadAllLines(filePath);
if (fileContent.Count() > 0)
{
string[] columns = fileContent[0].Split('\t');
for (int i = 0; i < columns.Count(); i++)
{
dtDataSource.Columns.Add(columns[i]);
}
for (int i = 1; i < fileContent.Count(); i++)
{
string[] rowData = fileContent[i].Split('\t');
dtDataSource.Rows.Add(rowData);
}
}
return dtDataSource;
}
This code works fine since i am generating 2003 excel file (.xls).
But if i am generating a 2007 (.xlsx) by changing the code to
Response.AddHeader("content-disposition", "attachment;filename=" + sFilename + ".xlsx");
i get an error like this.
I did my homework and came to know that this error is because the .xlsx file generated by my program is done by using HTML (markup language) XML (markup language) which should actually be done for a 2007 excel file.
My question is what changes should i do so that i get the desired result i.e. I get the 2007 excel sheet!!!
You can create the Excel with multiple Worksheet using DataSet like
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
using System.Data;
using System.IO;
[HttpPost]
public ActionResult CreateExcel(int id)
{
DataSet dataSet = new DataSet(); //Your Data Set
if (dataSet.Tables.Count > 0)
{
System.Data.DataTable dt1 = new System.Data.DataTable();
System.Data.DataTable dt2 = new System.Data.DataTable();
dt1 = dataSet.Tables[0];
dt2 = dataSet.Tables[1];
if (dt1.Rows.Count > 1 && dt2.Rows.Count > 1)
{
var excel = new Microsoft.Office.Interop.Excel.Application();
var workbook = excel.Workbooks.Add(true);
AddExcelSheet(dt1, workbook);
AddExcelSheet(dt2, workbook);
//KK-Save the excel file into server path
string strLocation = "~/Upload/TempExcel/";
string fName = "Report_" + DateTime.Now.ToString("MMddyyyyHHmmss") + ".xlsx";
string strPath = Path.Combine(Server.MapPath(strLocation), fName);
workbook.SaveAs(strPath);
workbook.Close();
//KK-Generate downloading link view page
System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearContent();
Response.Clear();
//Response.ContentType = "application/vnd.ms-excel"; //This is for office 2003
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("Content-Disposition", "attachment; filename=YourReport.xlsx");
Response.TransmitFile(strPath);
Response.Flush();
Response.End();
//KK-Deleting the file after downloading
if (System.IO.File.Exists(strPath))
System.IO.File.Delete(strPath);
}
}
return View();
}
/// <summary>
/// KK-This method add new Excel Worksheet using DataTable
/// </summary>
/// <param name="ds"></param>
private static void AddExcelSheet(System.Data.DataTable dt, Workbook wb)
{
Excel.Sheets sheets = wb.Sheets;
Excel.Worksheet newSheet = sheets.Add();
int iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
newSheet.Cells[1, iCol] = c.ColumnName;
newSheet.Cells[1, iCol].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.RoyalBlue);
newSheet.Cells[1, iCol].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
newSheet.Cells[1, iCol].Font.Bold = true;
newSheet.Cells[1, iCol].BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin);
}
int iRow = 0;
foreach (DataRow r in dt.Rows)
{
iRow++;
// add each row's cell data...
iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
newSheet.Cells[iRow + 1, iCol] = r[c.ColumnName];
newSheet.Cells[iRow + 1, iCol].BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin);
}
}
}
You should check the OpenXML SDK:
http://msdn.microsoft.com/en-us/library/office/gg278328.aspx
Alternatively, you can check the various commercial libraries listed here:
http://polymathprogrammer.com/spreadsheetopenxml/spreadsheetcodelibrariescomparison.pdf
I had a good experience with Aspose Cells.
PS: your code doesn't generate a valid xls file, but html that gets somehow correctly interpreted by excel.
You have to use extended libraries which I recommend using EPPlus which is a .net library that reads & writes Excel 2007/2010 files using the Open Office Xml format (xlsx).
Library
and then replace the code
protected void to_excel(object sender, EventArgs e)
{
string filepath = Path.Combine(Server.MapPath("~/Files"), fileupload.FileName);
fileupload.SaveAs(filepath);
string fname = fileupload.PostedFile.FileName;
DataTable dt = (DataTable)ReadToEnd(filepath);
string sFilename = fname.Substring(0, fname.IndexOf("."));
sFilename = sFilename + ".xlsx";
MemoryStream ms = DataTableToExcelXlsx(dt, "Sheet1");
ms.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);
HttpContext.Current.Response.StatusCode = 200;
HttpContext.Current.Response.End();
}
public void toexcel(DataTable dt, string Filename)
{
MemoryStream ms = DataTableToExcelXlsx(dt, "Sheet1");
ms.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Filename);
HttpContext.Current.Response.StatusCode = 200;
HttpContext.Current.Response.End();
}
public bool IsReusable
{
get { return false; }
}
public static MemoryStream DataTableToExcelXlsx(DataTable table, string sheetName)
{
MemoryStream Result = new MemoryStream();
ExcelPackage pack = new ExcelPackage();
ExcelWorksheet ws = pack.Workbook.Worksheets.Add(sheetName);
int col = 1;
int row = 1;
foreach (DataColumn column in table.Columns)
{
ws.Cells[row, col].Value = column.ColumnName.ToString();
col++;
}
col = 1;
row = 2;
foreach (DataRow rw in table.Rows)
{
foreach (DataColumn cl in table.Columns)
{
if (rw[cl.ColumnName] != DBNull.Value)
ws.Cells[row, col].Value = rw[cl.ColumnName].ToString();
col++;
}
row++;
col = 1;
}
pack.SaveAs(Result);
return Result;
}
I got this solution here

Categories

Resources