我使用以下代码通过http请求发送csv文件。代码运行正常,但文件未在客户端计算机上下载,不保存为菜单,不显示任何内容。我用于另一个报告的相同代码,它工作正常,文件也下载。我在本地主机上运行该项目。但不适用于按钮btnGenerateReport。
protected void btnGenerateReport_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
MHSProgressNotesBL oMHSProgressNote = new MHSProgressNotesBL();
int ClientId = Convert.ToInt32(ddlClients.SelectedValue);
int LocationId = Convert.ToInt32(ddlLocations.SelectedValue);
int PractitionerId = Convert.ToInt32(ddlPractitioner.SelectedValue);
dt = oMHSProgressNote.FetchBillingReport(LocationId, ClientId, PractitionerId, Convert.ToDateTime(txtNoteStartDate.Text), Convert.ToDateTime(txtNoteEndDate.Text));
WriteToCSV(dt);
}
private void WriteToCSV(DataTable dt)
{
try
{
string attachment = "attachment; filename=ClientRoster.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
//HttpContext.Current.Response.AddHeader("Pragma", "public");
WriteColumnName(dt);
foreach (DataRow clientdata in dt.Rows)
{
WriteUserInfo(clientdata);
}
HttpContext.Current.Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception e)
{ }
}
private void WriteColumnName(DataTable dt)
{
string columnNames = "";
// Write Header row
foreach (DataColumn item in dt.Columns)
{
if (item.ColumnName.Contains(','))
{
columnNames += "\"" + item.ColumnName + "\"";
}
else
{
columnNames += item.ColumnName + ",";
}
}
columnNames = columnNames.TrimEnd(',');
HttpContext.Current.Response.Write(columnNames);
HttpContext.Current.Response.Write(Environment.NewLine);
}
private void WriteUserInfo(DataRow clientDataRow)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (var item in clientDataRow.ItemArray)
{
AddComma((string)(item == System.DBNull.Value ? "" : item.ToString()), stringBuilder);
}
HttpContext.Current.Response.Write(stringBuilder.ToString().TrimEnd(','));
HttpContext.Current.Response.Write(Environment.NewLine);
}
private void AddComma(string value, StringBuilder stringBuilder)
{
if (value.Contains('"'))
{
value = value.Replace(@"""", @"""""");
value = "\"" + value + "\"";
}
else if (value.Contains(','))
{
value = "\"" + value + "\"";
}
stringBuilder.Append(value);
stringBuilder.Append(",");
}
答案 0 :(得分:0)
代码没问题.........主要问题是按钮btnGenerateReport位于更新面板内。错误正在上升:无法解析从服务器收到的消息。此错误的常见原因是通过调用Response.Write(),响应过滤器,HttpModules或服务器跟踪来修改响应。 详细信息:在“客户端,从业者”附近解析时出错。 将按钮放在更新面板之外后,代码工作正常。