我想將gridview轉換爲excel .xls
,但它會拋出錯誤,當我點擊確定後,它會轉換,但整個頁面出現在Excel中。 我想盡一切可能的內容類型,我有Excel 2010中如何將gridview轉換爲excel?
錯誤:
the file you are trying to convert is in a different format than specified by the file extension
代碼:
protected void btnTransactionDetails_Click(object sender, EventArgs e)
{
try
{
LabelResult.Text = "";
//GetReport();
int BusID= Convert.ToInt32(DropDownListBuses.SelectedValue);
int AccountID= Convert.ToInt32(DropDownList1.SelectedValue);
DateTime FromDate = Convert.ToDateTime(FromDateTextBox.Text);
DateTime ToDate = Convert.ToDateTime(ToDateTextBox.Text);
DataTable dt= new DataTable();
dt= Activities.GetLedger(AccountID, BusID, FromDate, ToDate);
GridViewLedger.DataSource= dt;
GridViewLedger.DataBind();
ViewState["Ledger"]= dt;
}
catch (Exception ex)
{
LabelResult.Text = ex.Message;
}
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
try
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=LedgerReport_" + FromDateTextBox.Text + " To " + ToDateTextBox.Text + ".xls");
Response.ContentType = "application/vnd.xlsx";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
htmlWrite.Write("<table><tr><td colspan='4'><center>Report Date : " + FromDateTextBox.Text + " To " + FromDateTextBox.Text + "</center></td></tr></table>");
GridViewLedger.AllowPaging = false;
GridViewLedger.AllowSorting = false;
// showAttendance();
GridViewLedger.DataSource = (DataSet)ViewState["Ledger"];
GridViewLedger.DataBind();
for (int i = 0; i <= GridViewLedger.Columns.Count - 1; i++)
{
GridViewLedger.HeaderRow.Cells[i].Style.Add("background-color", "#2FA4E7");
GridViewLedger.HeaderRow.Cells[i].Style.Add("color", "#FFFFFF");
}
for (int i = 0; i < GridViewLedger.Rows.Count; i++)
{
GridViewRow row = GridViewLedger.Rows[i];
row.Cells[3].Style.Add("background-color", "#73a839");
row.Cells[3].Style.Add("color", "#FFFFFF");
row.Cells[4].Style.Add("background-color", "#DA272D");
row.Cells[4].Style.Add("color", "#FFFFFF");
}
GridViewLedger.RenderControl(htmlWrite);
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Write(stringWrite.ToString());
Response.End();
}
catch (Exception x)
{
// ResultLabel.ResultLabelAttributes(x.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
}
}
綁定gridview從DataSet,然後在谷歌DataSet搜索到Excel。 – mybirthname 2015-03-02 08:48:58
檢查此鏈接http://www.aspsnippets.com/Articles/Export-GridView-to-Excel-in-ASPNet-with-Formatting-using-C-and-VBNet.aspx – 2015-03-02 08:52:07
導出數據表到Excel,你可以嘗試通過使用保存在ViewState [「Ledger」] = dt中的數據表(因爲您已經將數據表保存在視圖狀態中)請通過http://stackoverflow.com/questions/8207869/how-to-export-datatable -to-excel-in-c-sharp – 2015-03-02 09:26:05