I am trying to generate excel with following code
public void GenerateExcel(string reportName, DataTable dt)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application/ms-excel";
Response.Write(#"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
Response.AddHeader("Content-Disposition", "attachment;filename= " + reportName + ".xls");
Response.Charset = "utf-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
StringWriter ws = new StringWriter();
ws.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
// ws.Write("<BR><BR><BR>");
//sets the table border, cell spacing, border color, font of the text, background, foreground, font height
ws.Write("<Table border='1' bgColor='#ffffff' " +
"borderColor='#000000' cellSpacing='0' cellPadding='0' " +
"style='font-size:10.0pt; font-family:Calibri; background:white;'>");
string strBoldCell = "<TD bgColor='#c9c7c3' style=\"font-weight: bold\">{0}</TD>";
string strRedCell = "<TD style=\"background-color:#ff4d4d\">{0}</TD>";
string strCell = "<TD>{0}</TD>";
string strColSpan = "<TD colspan={0} style=\"font-weight: bold\">{1}</TD>";
int r;
int c;
if (dt.Rows.Count > 0)
{
try
{
ws.Write("<TR>");
for (c = 0; c < dt.Columns.Count; c++)
{
ws.Write(string.Format(strBoldCell, dt.Columns[c].ColumnName).Replace("_", ""));
}
ws.Write("</TR>");
ws.Write("\n");
for (r = 0; r < dt.Rows.Count; r++)
{
ws.Write("<TR>");
for (c = 0; c < dt.Columns.Count; c++)
{
if (string.IsNullOrEmpty(dt.Rows[r][dt.Columns[c].ColumnName].ToString()) == false)
{
if (dt.Rows[r]["Comment"].ToString() != null && dt.Rows[r]["Comment"].ToString() != "")
{
ws.Write(string.Format(strRedCell, dt.Rows[r][dt.Columns[c].ColumnName].ToString().Replace('_', ' ')));
}
else
{
ws.Write(string.Format(strCell, dt.Rows[r][dt.Columns[c].ColumnName].ToString().Replace('_', ' ')));
}
}
else
{
if (dt.Rows[r]["Comment"].ToString() != null && dt.Rows[r]["Comment"].ToString() != "")
{
ws.Write(string.Format(strRedCell, " "));
}
else
{
ws.Write(string.Format(strCell, " "));
}
}
}
ws.Write("</TR>");
ws.Write("\n");
}
}
catch (Exception ex)
{
throw ex;
}
}
else
{
ws.Write("<Tr>");
ws.Write(string.Format(strColSpan, 10, "No records found"));
ws.Write("</Tr>");
}
ws.Write("</Table>");
ws.Write("</Font>");
Response.Write(ws.ToString());
Response.Flush();
Response.End();
}
by calling above method in main method as follows
if (Cnt != 0)
{
TempData["Error"] = "There were issues with the Excel Import: Total Records: " + result.Rows.Count+" Error Row Count: "+Cnt;
}
else
{
TempData["Error"] = "No error found in given excel: Total Records: " + result.Rows.Count;
}
GenerateExcel("OutputFile" + DateTime.Now.ToString("MMddyyyyhhmmss"), result);
return View();
also trying to pass Tempdata to view but the problem is excel is generating successfully but tempdata does not showing anything in view.
if i comment the code of calling GenerateExcel method tempdata is perfectly showing on view..why this is happening?
Please Try moving calling function before setting tempdata like:
GenerateExcel("OutputFile" + DateTime.Now.ToString("MMddyyyyhhmmss"), result);
if (Cnt != 0)
{
TempData["Error"] = "There were issues with the Excel Import: Total Records: " + result.Rows.Count+" Error Row Count: "+Cnt;
}
else
{
TempData["Error"] = "No error found in given excel: Total Records: " + result.Rows.Count;
}
return View();
Related
I'm working on a C# asp.net project and can't seem to get the "exporting to a .txt file from a grid view" to work.
protected void ExportGridToText() {
BindGridView();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
StringBuilder Rowbind = new StringBuilder();
Response.ContentType = "application/text";
Response.AddHeader("Content-Disposition", "attachment;filename=GlogData.txt");
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
Response.Cache.SetCacheability(HttpCacheability.NoCache);
gvLog.DataBind();
for (int i = 2; i < gvLog.Columns.Count; i++)
{
Rowbind.Append("\"" + gvLog.Columns[i].HeaderText + "\"" + ',');
}
Rowbind.Append("\n");
for (int j = 0; j < gvLog.Rows.Count; j++)
{
for (int k = 0; k < gvLog.Columns.Count; k++)
{
Rowbind.Append("\"" + gvLog.Rows[j].Cells[k].Text + "\"" + ',');
Rowbind.Replace("<", "<");
Rowbind.Replace(">", ">");
}
Rowbind.Append("\n");
}
gvLog.AllowPaging = false;
Response.Output.Write(Rowbind.ToString());
Response.Flush();
Response.End();
}
Evrytime I run the code I get a error message:
Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed
Why is it giving me this error?
How do I fix it?
Is it possible to get the data from the source... This is under the get Button that populates the GridView:
protected void GetLogBtn_Click(object sender, EventArgs e)
{
string sBeginDate = BeginDate.Text;
string sEndDate = EndDate.Text;
JObject vResultJson = new JObject();
FKWebCmdTrans cmdTrans = new FKWebCmdTrans();
DateTime dtBegin, dtEnd;
if (sBeginDate.Length > 0)
{
try
{
dtBegin = Convert.ToDateTime(sBeginDate);
sBeginDate = FKWebTools.GetFKTimeString14(dtBegin);
vResultJson.Add("begin_time", sBeginDate);
}
catch
{
BeginDate.Text = "";
}
}
if (sEndDate.Length > 0)
{
try
{
dtEnd = Convert.ToDateTime(sEndDate);
sEndDate = FKWebTools.GetFKTimeString14(dtEnd);
vResultJson.Add("end_time", sEndDate);
}
catch
{
EndDate.Text = "";
}
}
try
{
string sFinal = vResultJson.ToString(Formatting.None);
byte[] strParam = new byte[0];
cmdTrans.CreateBSCommBufferFromString(sFinal, out strParam);
mTransIdTxt.Text = FKWebTools.MakeCmd(msqlConn, "GET_LOG_DATA", mDevId, strParam);
Session["operation"] = GET_LOG_DATA;
GetLogBtn.Enabled = false;
ClearBtn.Enabled = false;
Timer.Enabled = true;
}
catch (Exception ex)
{
StatusTxt.Text = "Fail! Get Log Data! " + ex.ToString();
}
}
This is under the BindGridView:
private void BindGridView()
{
try
{
string mTransid = mTransIdTxt.Text;
string strSelectCmd = "SELECT COUNT(*) FROM tbl_fkcmd_trans_cmd_result_log_data where trans_id = '" + mTransid + "'";
SqlCommand sqlCmd = new SqlCommand(strSelectCmd, msqlConn);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
if (sqlReader.HasRows)
{
if (sqlReader.Read())
nCount = sqlReader.GetInt32(0);
}
sqlReader.Close();
sqlCmd.Dispose();
{
DataSet dsLog = new DataSet();
strSelectCmd = "SELECT * FROM tbl_fkcmd_trans_cmd_result_log_data where trans_id = '" + mTransid + "'";
SqlDataAdapter da = new SqlDataAdapter(strSelectCmd, msqlConn);
// conn.Open();
da.Fill(dsLog, "tbl_fkcmd_trans_cmd_result_log_data");
DataView dvLog = dsLog.Tables["tbl_fkcmd_trans_cmd_result_log_data"].DefaultView;
gvLog.DataSource = dvLog;
gvLog.DataBind();
StatusTxt.Text = " Total Count : " + Convert.ToString(nCount) + " Current Time :" + DateTime.Now.ToString("HH:mm:ss tt");
}
}
catch (Exception ex)
{
StatusTxt.Text = ex.ToString();
}
}
I hope this helps
Thanks in advance
Following Code is For Excel Mainly...but its successfully converting gridview to .txt file just need a little workaround..
public void ExportToExcel(System.Web.UI.WebControls.GridView controlname, string sheetname)
{
HttpContext context = HttpContext.Current;
context.Response.ClearContent();
context.Response.Buffer = true;
context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", sheetname + ".txt"));
context.Response.ContentType = "application/text";
// context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", sheetname + ".xls"));
// context.Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
//Change the Header Row back to white color
controlname.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < controlname.HeaderRow.Cells.Count; i++)
{
controlname.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in controlname.Rows)
{
gvrow.BackColor = Color.White;
if (j <= controlname.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
controlname.RenderControl(htw);
context.Response.Write(sw.ToString());
context.Response.End();
}
Hi I have problem to return right encoded file.
finalString is here only for my control of encoding and show me right strings, but returned excel file dont contain right czech characters... (Č č š Š Ž etc...) Can someone help me?
byte[] bytes = encode.GetBytes(str.ToString());
string finalString = encode.GetString(bytes);
Here is complete class:
public async Task<IActionResult> ExportExcel()
{
// List<Material> obj = new List<Material>();
// obj = await _context.Material.ToListAsync();
StringBuilder str = new StringBuilder();
str.Append("<table border=`" + "1px" + "`b>");
str.Append("<tr>");
str.Append("<td><b>Id</b></td>");
str.Append("<td><b>Name</b></td>");
str.Append("</tr>");
// foreach (Material val in obj)
// {
str.Append("<tr>");
str.Append("<td>" + "0" + "</td>");
str.Append("<td>" + Česnek + "</td>");
str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.Name.ToString() + "</font></td>");
str.Append("</tr>");
// }
str.Append("</table>");
string uc = Configuration.UserCulture;
int codepage = 1250; // _cultureDataProvider.GetAnsiCodePage(uc);
Encoding encode = Encoding.GetEncoding(codepage);
byte[] bytes = encode.GetBytes(str.ToString());
string finalString = encode.GetString(bytes);
MemoryStream stream = new MemoryStream(bytes);
return File(stream, "application/vnd.ms-excel", "excel.xls");
/*
HttpContext.Response.Headers.Add("content-disposition", "attachment; filename=Information" + DateTime.Now.Year.ToString() + ".xls");
this.Response.ContentType = "application/vnd.ms-excel";
byte[] temp = System.Text.Encoding.ASCII.GetBytes(str.ToString());
return File(temp, "application/vnd.ms-excel");
*/
}
I was able to solve it after one day - csv and tab .txt file solution: (working under Core CLR)
public async Task<IActionResult> Export(string type)
{
string _OuputType = type.ToLower().Trim();
string _delimiter = _OuputType.Contains("csv") ? ";" : String.Empty;
_delimiter = _OuputType.Contains("txt") ? "" : _delimiter;
IEnumerable<Material> data = await _context.Material.Include(m => m.Unit).ToListAsync();
StringBuilder str = new StringBuilder();
//file name
string fileName = "Material-" + DateTime.Now.ToString("dd_MM_yyyy-H_mm_ss");
//head
str.Append("Name" + _delimiter + "\t");
str.Append("AutoPlan" + _delimiter + "\t");
str.Append("QuantityMinStock" + _delimiter + "\t");
str.Append("QuantityMaxStock" + _delimiter + "\t");
str.Append("QuantityPurchase" + _delimiter + "\t");
str.Append("Unit" + _delimiter + "\t");
str.Append("\r\n");
//data
foreach (Material m in data)
{
str.Append(m.id + _delimiter + "\t");
str.Append(m.Name + _delimiter + "\t");
str.Append(m.AutoPlan + _delimiter + "\t");
str.Append(m.QuantityMinStock + _delimiter + "\t");
str.Append(m.QuantityMaxStock + _delimiter + "\t");
str.Append(m.QuantityPurchase + _delimiter + "\t");
str.Append(m.Unit.LocalizedCode + _delimiter + "\t");
str.Append("\r\n");
}
// int codepage = _cultureDataProvider.GetAnsiCodePage(Configuration.UserCulture); == This is my service to get code page (example: 1250, or 1252 etc...)
Encoding encode = Encoding.GetEncoding(_cultureDataProvider.GetAnsiCodePage(Configuration.UserCulture));
byte[] bytes = encode.GetBytes(str.ToString());
if (_OuputType == "txt"){return File(bytes, "text/plain", fileName + ".txt");}
return File(bytes, "application/msexcel", fileName + ".csv");
}
ANSI does not provide valid encoding for Č, č, š, Š, Ž you should look for more suitable codepages like UTF-8, UTF-16, UTF-32, etc....
byte[] bytes = Encoding.UTF8.GetBytes(str.ToString());
string finalString = Encoding.UTF8.GetString(bytes);
Did you try to work using Office Interop? It would be more ease and right way to work with Excel.
Here is simple worksheet manager
public class ExcelManager
{
public ExcelManager()
{
ItsApplication = null;
ItsWorkbook = null;
ItsWorksheet = null;
AppInitialization = false;
WrbInitialization = false;
WrsInitialization = false;
}
/*////////////////////////////////////////////////////*/
public void Initialize(bool visible)
{
try
{
if (ItsApplication == null)
{
ItsApplication = new Microsoft.Office.Interop.Excel.Application();
ItsApplication.SheetsInNewWorkbook = 1;
ItsApplication.Visible = visible;
AppInitialization = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public void CreateWorkbook()
{
try
{
if (ApplicationInitialized)
{
ItsWorkbook = ItsApplication.Workbooks.Add(MissingValue);
WrbInitialization = true;
}
else
MessageBox.Show(
"Couldnot create workbook!\n" +
"App instance didnot initialized!",
"Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public void CreateWorksheet()
{
try
{
if (WorkbookInitialized)
{
ItsWorksheet = ItsWorkbook.Worksheets.Add(MissingValue,
MissingValue, MissingValue, MissingValue);
WrsInitialization = true;
CurrentRow = 1;
}
else
MessageBox.Show(
"Couldnot create worksheet!\n" +
"Workbook didnot created!",
"Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public void SetText(string text,int bold,int italic,int cells_offset)
{
try
{
if (WorksheetInitialized)
{
ArrayList lines_list = new ArrayList();
string curr_line = "";
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '\n' || (i == text.Length - 1))
{
lines_list.Add(curr_line);
curr_line = "";
}
curr_line += text[i];
}
CurrentRow += cells_offset;
foreach (object line in lines_list)
{
Range text_range =
ItsWorksheet.get_Range("A" + CurrentRow, "A" + CurrentRow);
text_range.Font.Bold = bold;
text_range.Font.Italic = italic;
text_range.Value2 = line;
text_range.WrapText = false;
CurrentRow++;
}
}
else
MessageBox.Show(
MessageBox.Show(
"Cannot output any text!\n" +
"Worksheed didnot created!",
"Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public void SetData(System.Data.DataTable table, int bold, int italic,int rows_offset)
{
try
{
if (WorksheetInitialized)
{
CurrentRow += rows_offset;
int TableRows = table.Rows.Count;
int TableCols = table.Columns.Count;
char ACol = 'A';
Range TableRange = ItsWorksheet.get_Range("A" + CurrentRow,
((char)((int)ACol + TableCols - 1)).ToString() + (CurrentRow + TableRows).ToString());
TableRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
for (int i = 0; i < TableCols; i++)
{
Range names_range = ItsWorksheet.get_Range(((char)((int)ACol + i)).ToString() + CurrentRow,
((char)((int)ACol + i)).ToString() + CurrentRow);
names_range.Value2 = table.Columns[i].ColumnName;
}
for (int i = 1; i < TableRows + 1; i++)
{
for (int j = 0; j < TableCols; j++)
{
Range cell_range = ItsWorksheet.get_Range(((char)((int)ACol + j)).ToString() + (CurrentRow + i),
((char)((int)ACol + j)).ToString() + (CurrentRow + i));
cell_range.Value2 = table.Rows[i - 1].ItemArray[j];
cell_range.Font.Bold = bold;
cell_range.Font.Italic = italic;
}
}
CurrentRow += TableRows;
}
else
MessageBox.Show(
"Cannot output any text!\n" +
"Worksheed didnot created!",
"Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public void SaveCurrentWorksheet(string filename)
{
try
{
ItsWorksheet.SaveAs(filename,
MissingValue,
MissingValue,
MissingValue,
MissingValue,
MissingValue,
MissingValue,
MissingValue,
MissingValue,
MissingValue);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
public void CloseCurrentWorksheet()
{
if (WorkbookInitialized)
{
ItsWorkbook.Close(MissingValue,
MissingValue,
MissingValue);
ItsApplication.Quit();
WrbInitialization = false;
WrsInitialization = false;
AppInitialization = false;
}
}
public bool ApplicationInitialized
{
get
{
return AppInitialization;
}
}
public bool WorkbookInitialized
{
get
{
return WrbInitialization;
}
}
public bool WorksheetInitialized
{
get
{
return WrsInitialization;
}
}
////////////////////////////////////////////////////////
private _Application ItsApplication;
private _Worksheet ItsWorksheet;
private _Workbook ItsWorkbook;
// Initialization flags
private bool AppInitialization;
private bool WrbInitialization;
private bool WrsInitialization;
// Positioning text in rows
private int CurrentRow;
////////////////////////////////////////////////////////
// Define static members of class
private static object MissingValue = System.Reflection.Missing.Value;
private static object EndOfDocument = "\\endofdoc";
}
You can use SetData method to print tables to excel files.
Simple instruction:
Create instance of class;
Initialize world application by calling public void Initialize(bool visible) visible controll the wisibility of Excell window.
Create new workbook by calling CreateWorkbok;
And worksheet by CreateWorksheet;
Work with worksheet SetData - prints table DataTable;
Work with text SetText.
To save and close use SaveCurrentWorksheet and CloseCurrentWorksheet.
ExcelManager excel_manager = new ExcelManager()
excel_manager.Initialize(true);
excel_manager.CreateWorkbook();
excel_manager.CreateWorksheet();
excel_manager.SetText("Česnek!", 1, 0, 0);
excel_manager.SetData(systemTable, 0, 0, 2);
excel_manager.SetText("Лог консолі!", 1, 0, 3);
The result of calls:
Or you can use Open XML SDK for Office, to support multitask in your web application.
I have below functions that take Data Table and convert to excel and prompt user to download the excel.
May I know how can I change the function so that it is save to my local directory instead of download?
public static void ExportDataTableToExcel(DataTable table, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
string attachment = "attachment; filename=" + name + ".xls";
context.Response.ClearContent();
context.Response.AddHeader("content-disposition", attachment);
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.ContentEncoding = System.Text.Encoding.Unicode;
context.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
string tab = "";
foreach (DataColumn dc in table.Columns)
{
context.Response.Write(tab + dc.ColumnName);
tab = "\t";
}
context.Response.Write("\n");
int i;
foreach (DataRow dr in table.Rows)
{
tab = "";
for (i = 0; i < table.Columns.Count; i++)
{
context.Response.Write(tab + "=\"" + dr[i].ToString() + "\"");
tab = "\t";
}
context.Response.Write("\n");
}
context.Response.End();
}
Found and implemented the function
public static bool SaveDataTableToExcel(DataTable table, string savePath)
{
//open file
StreamWriter wr = new StreamWriter(savePath, false, Encoding.Unicode);
try
{
for (int i = 0; i < table.Columns.Count; i++)
{
wr.Write(table.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (table.Rows.Count); i++)
{
for (int j = 0; j < table.Columns.Count; j++)
{
if (table.Rows[i][j] != null)
{
wr.Write("=\"" + Convert.ToString(table.Rows[i][j]) + "\"" + "\t");
}
else
{
wr.Write("\t");
}
}
//go to next line
wr.WriteLine();
}
//close file
wr.Close();
}
catch (Exception ex)
{
LogError(ex);
return false;
}
return true;
}
In thst code i have us two database tabele and fetch data in datatable then write all the data in the csv files with help of stream writer then add both the file in a folder and download in a zip form but sometimes its shows an error The process cannot access the file 'xxxxx.zip' because it is being used by another process.
protected void btnExportToCSV_Click(object sender, EventArgs e)
{
//Work Detail
blExportToExcel obj = new blExportToExcel();
System.Data.DataTable dtTechSanc = blDbFunction.GetTechSanc(ddlAgency.SelectedValue.ToString(), ddlDivision.SelectedValue.ToString(), ddlDistrict.SelectedValue.ToString(), ddlMC.SelectedValue.ToString(), ddlScheme.SelectedValue.ToString(), ddlUserType.SelectedValue.ToString(), ddlWorkType.SelectedValue.ToString(), ddlWorkNature.SelectedValue.ToString(), ddlWorkStatus.SelectedValue.ToString(), ((prpSessionData)(Session["sUserInfo"])).UId);
dtTechSanc.Columns["Id"].ColumnName = "WorkCode";
dtTechSanc.Columns["TSId"].ColumnName = "Id";
string filenamezip = "ZipFile\\TechSancRevision_" + DateTime.Now.ToString().Replace(":", "-").Replace("/", "-") + ".zip";
string strPathAndQuery = HttpContext.Current.Request.PhysicalApplicationPath;
string paths = strPathAndQuery + filenamezip;
ZipFile z = ZipFile.Create(paths);
z.BeginUpdate();
if (dtTechSanc.Rows.Count > 0)
{
string tmpPath = Server.MapPath("FileTemplates");
string tmpFileName = "TechSancRevision.csv";
tmpPath = #"" + tmpPath.Replace("/", "\\").Replace("\\Department", "") + "\\" + tmpFileName;
StreamWriter sw = new StreamWriter(tmpPath, false);
int columnCount = dtTechSanc.Columns.Count;
for (int i = 0; i < columnCount; i++)
{
sw.Write(dtTechSanc.Columns[i]);
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtTechSanc.Rows)
{
for (int i = 0; i < columnCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
z.Add(tmpPath, tmpFileName);
z.CommitUpdate();
}
//Fund Allocation
System.Data.DataTable dtFA = blDbFunction.GetFundAllocationTS(ddlAgency.SelectedValue.ToString(), ddlDivision.SelectedValue.ToString(), ddlDistrict.SelectedValue.ToString(), ddlMC.SelectedValue.ToString(), ddlScheme.SelectedValue.ToString(), ddlUserType.SelectedValue.ToString(), ddlWorkType.SelectedValue.ToString(), ddlWorkNature.SelectedValue.ToString(), ddlWorkStatus.SelectedValue.ToString(), ((prpSessionData)(Session["sUserInfo"])).UId);
if (dtFA.Rows.Count > 0)
{
z.BeginUpdate();
string tmpPath = Server.MapPath("FileTemplates");
string tmpFileName = "FundsAllocationRevision.csv";
tmpPath = #"" + tmpPath.Replace("/", "\\").Replace("\\Department", "") + "\\" + tmpFileName;
dtFA.Columns["FAId"].ColumnName = "Id";
dtFA.Columns["WorkId"].ColumnName = "WorkCode";
StreamWriter sw = new StreamWriter(tmpPath, false);
int columnCount = dtFA.Columns.Count;
for (int i = 0; i < columnCount; i++)
{
sw.Write(dtFA.Columns[i]);
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtFA.Rows)
{
for (int i = 0; i < columnCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
z.Add(tmpPath, tmpFileName);
z.CommitUpdate();
z.Close();
}
System.IO.FileInfo file = new System.IO.FileInfo(paths);
Response.ContentType = "application/text";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + Path.GetFileName(paths));
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);/// error shows here
Response.End();
}
}
I am not sure this will help you or not but i am transmitting zip using below code , please try it. It works perfectly and in use from past 2 years.
Response.ContentType = "application/zip";
Response.AppendHeader("Content-Disposition", "attachment; filename=Test.zip")
Response.TransmitFile(#"C:\Test.zip");
Response.Flush();
// Prevents any other content from being sent to the browser
Response.SuppressContent = true;
// Directs the thread to finish, bypassing additional processing
HttpContext.Current.ApplicationInstance.CompleteRequest();
I am using VS 2008,C#.net,asp.net.
I am exporting the data to excel 2003.
The exported excel is of the type .xls in IE and Chrome.
But it is not .xls type in mozilla.When open that file, it is asking which program you want to open?
What is the reason?
the program is mentioned below.
## Heading ##
private void ExportDataSetToExcel()
{
try
{
DataSet Ds = new DataSet();
DataTable DT = new DataTable();
string param = hidType.Get("Type").ToString();
string[] codes = param.Split('.');
if (codes.Length == 1)
FillGrid(Convert.ToString(param));
else
FillDrillDownGrid(codes[1], codes[0]);
if (hidType.Get("Type").ToString() == "2")
{
DT.Columns.Add("<b>Sub Group Code</b>");
DT.Columns.Add("<b>Account Sub Group</b>");
}
else if (hidType.Get("Type").ToString() == "3")
{
DT.Columns.Add("<b>Group Code</b>");
DT.Columns.Add("<b>Account Group</b>");
}
else
{
DT.Columns.Add("<b>Acc.Head Code</b>");
DT.Columns.Add("<b>Account Head</b>");
}
DT.Columns.Add("<b>Debit</b>");
DT.Columns.Add("<b>Credit</b>");
for (int j = 0; j < grdTrialBal.VisibleRowCount; j++)
{
DataRow DR;
DR = DT.NewRow();
if (hidType.Get("Type").ToString() == "2")
{
DR["<b>Sub Group Code</b>"] = grdTrialBal.GetRowValues(j, "ahdUserCode");
DR["<b>Account Sub Group</b>"] = grdTrialBal.GetRowValues(j, "ahdname");
}
else if (hidType.Get("Type").ToString() == "3")
{
DR["<b>Group Code</b>"] = grdTrialBal.GetRowValues(j, "ahdUserCode");
DR["<b>Account Group</b>"] = grdTrialBal.GetRowValues(j, "ahdname");
}
else
{
DR["<b>Acc.Head Code</b>"] = grdTrialBal.GetRowValues(j, "ahdUserCode");
DR["<b>Account Head</b>"] = grdTrialBal.GetRowValues(j, "ahdname");
}
if (Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdDrAmt")) != 0)
{
DR["<b>Debit</b>"] = Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdDrAmt"));
}
if (Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdCrAmt")) != 0)
{
DR["<b>Credit</b>"] = Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdCrAmt"));
}
CrAmount = CrAmount + Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdCrAmt"));
DrAmount = DrAmount + Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdDrAmt"));
DT.Rows.Add(DR);
}
DataRow Dr1;
Dr1 = DT.NewRow();
if (hidType.Get("Type").ToString() == "2")
{
Dr1["<b>Sub Group Code</b>"] = "";
Dr1["<b>Account Sub Group</b>"] = "<b>Total</b>";
}
else if (hidType.Get("Type").ToString() == "3")
{
Dr1["<b>Group Code</b>"] = "";
Dr1["<b>Account Group</b>"] = "<b>Total</b>";
}
else
{
Dr1["<b>Acc.Head Code</b>"] = "";
Dr1["<b>Account Head</b>"] = "<b>Total</b>";
}
Dr1["<b>Debit</b>"] = "<b>" + DrAmount.ToString("#0.#0") + "</b>";
Dr1["<b>Credit</b>"] = "<b>" + CrAmount.ToString("#0.#0") + "</b>";
DT.Rows.Add(Dr1);
DataGrid dg = new DataGrid();
dg.DataSource = DT;
dg.DataBind();
String strFileName = "Trial Balance Account Group Wise.xls";
if (hidType.Get("Type").ToString() == "2")
{
strFileName = "Trial Balance Account Sub Group Wise.xls";
}
else if (hidType.Get("Type").ToString() == "3")
{
strFileName = "Trial Balance Account Group Wise.xls";
}
else
{
strFileName = "Trial Balance Account Head Wise.xls";
}
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
CommonFunctions cf = new CommonFunctions();
String[] aTo = mskToDate1.Text.Split(new[] { '/', '-' });
String dTo;
dTo = aTo[0] + "/" + cf.getMonthName(Convert.ToInt32(aTo[1])) + "/" + aTo[2];
if (hidType.Get("Type").ToString() == "2")
{
htw.WriteLine("<b><u><font size='5'>" + "Trial Balance - Account Sub Group Wise - As on :" + dTo + " </font></u></b>");
}
else if (hidType.Get("Type").ToString() == "3")
{
htw.WriteLine("<b><u><font size='5'>" + "Trial Balance - Account Group Wise - As on :" + dTo + " </font></u></b>");
}
else
{
htw.WriteLine("<b><u><font size='5'>" + "Trial Balance - Account Head Wise - As on : " + dTo + " </font></u></b>");
}
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
dg = null;
dg.Dispose();
}
catch (Exception ex)
{
}
}
set filename in double quotes
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + strFileName+ "\"");