C#中把datagridview中显示的数据导出到excel中
本人用的是LINQ写的,想要用一个按钮实现datagridview中的数据的导出到excel,不知道怎么写,请教高人写下具体步骤和代码,不胜感激!...
本人用的是LINQ写的,想要用一个按钮实现datagridview中的数据的导出到excel,不知道怎么写,请教高人写下具体步骤和代码,不胜感激!
展开
3个回答
展开全部
private void btnSave_Click(object sender, EventArgs e)
{
//AsyncCallback callback = new AsyncCallback(ExportCompleted);
//ExportMediator.PerformExportAsync(dataGridView,callback);
if(ExportMediator.PerformExport(dataGridView,FileType.Html))
MessageBox.Show(this,"数据保存成功","成功提示",MessageBoxButtons.OK,MessageBoxIcon.Information,MessageBoxDefaultButton.Button1);
}
public static class ExportMediator
{
public static bool ShowSaveExcelDialog(out string fileName, FileType type)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "���Excel 文件";
saveFileDialog.Filter = "Excel 文件(*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = false;
saveFileDialog.CreatePrompt = false; //���
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
fileName = saveFileDialog.FileName;
return true;
}
else
{
fileName = null;
return false;
}
}
public static bool Export(DataGridView dataGridView, string fileName, FileType type)
{
switch (type)
{
case FileType.Excel:
return Export2Excel(dataGridView, fileName);
break;
case FileType.Html:
return Export2Html(dataGridView,fileName);
break;
default:
return false;
break;
}
}
public static bool Export2Excel(DataGridView dataGridView,string xlsName)
{
if (dataGridView == null || xlsName == null || xlsName.Trim() == "")
return false;
//object objOpt = Missing.Value;
Excel.Application
xlApp = new Excel.ApplicationClass();
xlApp.DefaultFilePath = "";
xlApp.DisplayAlerts = false; //Ӹ�Ϊfalse
xlApp.SheetsInNewWorkbook = 1;
Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
//��DataTable�������Excel���һ�
int columnIndex = 1;
foreach (DataGridViewColumn column in dataGridView.Columns)
{
//if (column.Visible)
xlApp.Cells[1, columnIndex++] = column.HeaderText;
}
//н�DataTable�е���ݵ��Excel��
int rowIndex = 2;
foreach (DataGridViewRow row in dataGridView.Rows)
{
columnIndex = 1;
foreach (DataGridViewCell cell in row.Cells)
{
xlApp.Cells[rowIndex, columnIndex++] = cell.Value;
}
rowIndex++;
}
xlBook.SaveCopyAs(xlsName);
//if (xlBook.Saved == true)
// xlBook.Close(true, objOpt, objOpt);
xlApp.Quit();
return true;
}
public static bool Export2Html(DataGridView dataGridView, string htmlName)
{
if (dataGridView == null || htmlName == null || htmlName.Trim() == "")
return false;
StringBuilder sbHtml = new StringBuilder("<html><head><title>���ʷ���</title><meta http-equiv='Content-Type' content='text/html; charset=utf-8'/></head>");
sbHtml.Append("<body>\n<table border='1' cellPadding='1' cellSpacing='0'>\n");
sbHtml.Append("<tr>");
foreach (DataGridViewColumn column in dataGridView.Columns)
{
if (column.Visible)
sbHtml.Append(string.Format("<td>{0}</td>", GetSafeString(column.HeaderText)));
}
sbHtml.Append("</tr>\n");
//DataTable�е���ݵ��Excel��
foreach (DataGridViewRow row in dataGridView.Rows)
{
sbHtml.Append("<tr>");
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Visible)
sbHtml.Append(string.Format("<td>{0}</td>", GetSafeString(cell.Value)));
}
sbHtml.Append("</tr>\n");
}
sbHtml.Append("</table></body></html>");
using (StreamWriter write = new StreamWriter(htmlName))
{
write.Write(sbHtml.ToString());
write.Close();
}
return true;
}
public static bool PerformExport(DataGridView dataGridView, FileType type)
{
string fileName;
return ShowSaveExcelDialog(out fileName, type)
&& Export(dataGridView, fileName, type);
}
//public static bool ExportToText(SaleInfo saleInfo, string fileName)
//{
// StreamWriter sw = new StreamWriter(fileName);
// //sw.WriteLine("" + saleInfo.
//}
static string GetSafeString(object obj)
{
return obj.ToString().Replace("<", "<").Replace(">", ">");
}
}
public enum FileType
{
Excel,
Html
}
{
//AsyncCallback callback = new AsyncCallback(ExportCompleted);
//ExportMediator.PerformExportAsync(dataGridView,callback);
if(ExportMediator.PerformExport(dataGridView,FileType.Html))
MessageBox.Show(this,"数据保存成功","成功提示",MessageBoxButtons.OK,MessageBoxIcon.Information,MessageBoxDefaultButton.Button1);
}
public static class ExportMediator
{
public static bool ShowSaveExcelDialog(out string fileName, FileType type)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "���Excel 文件";
saveFileDialog.Filter = "Excel 文件(*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = false;
saveFileDialog.CreatePrompt = false; //���
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
fileName = saveFileDialog.FileName;
return true;
}
else
{
fileName = null;
return false;
}
}
public static bool Export(DataGridView dataGridView, string fileName, FileType type)
{
switch (type)
{
case FileType.Excel:
return Export2Excel(dataGridView, fileName);
break;
case FileType.Html:
return Export2Html(dataGridView,fileName);
break;
default:
return false;
break;
}
}
public static bool Export2Excel(DataGridView dataGridView,string xlsName)
{
if (dataGridView == null || xlsName == null || xlsName.Trim() == "")
return false;
//object objOpt = Missing.Value;
Excel.Application
xlApp = new Excel.ApplicationClass();
xlApp.DefaultFilePath = "";
xlApp.DisplayAlerts = false; //Ӹ�Ϊfalse
xlApp.SheetsInNewWorkbook = 1;
Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
//��DataTable�������Excel���һ�
int columnIndex = 1;
foreach (DataGridViewColumn column in dataGridView.Columns)
{
//if (column.Visible)
xlApp.Cells[1, columnIndex++] = column.HeaderText;
}
//н�DataTable�е���ݵ��Excel��
int rowIndex = 2;
foreach (DataGridViewRow row in dataGridView.Rows)
{
columnIndex = 1;
foreach (DataGridViewCell cell in row.Cells)
{
xlApp.Cells[rowIndex, columnIndex++] = cell.Value;
}
rowIndex++;
}
xlBook.SaveCopyAs(xlsName);
//if (xlBook.Saved == true)
// xlBook.Close(true, objOpt, objOpt);
xlApp.Quit();
return true;
}
public static bool Export2Html(DataGridView dataGridView, string htmlName)
{
if (dataGridView == null || htmlName == null || htmlName.Trim() == "")
return false;
StringBuilder sbHtml = new StringBuilder("<html><head><title>���ʷ���</title><meta http-equiv='Content-Type' content='text/html; charset=utf-8'/></head>");
sbHtml.Append("<body>\n<table border='1' cellPadding='1' cellSpacing='0'>\n");
sbHtml.Append("<tr>");
foreach (DataGridViewColumn column in dataGridView.Columns)
{
if (column.Visible)
sbHtml.Append(string.Format("<td>{0}</td>", GetSafeString(column.HeaderText)));
}
sbHtml.Append("</tr>\n");
//DataTable�е���ݵ��Excel��
foreach (DataGridViewRow row in dataGridView.Rows)
{
sbHtml.Append("<tr>");
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Visible)
sbHtml.Append(string.Format("<td>{0}</td>", GetSafeString(cell.Value)));
}
sbHtml.Append("</tr>\n");
}
sbHtml.Append("</table></body></html>");
using (StreamWriter write = new StreamWriter(htmlName))
{
write.Write(sbHtml.ToString());
write.Close();
}
return true;
}
public static bool PerformExport(DataGridView dataGridView, FileType type)
{
string fileName;
return ShowSaveExcelDialog(out fileName, type)
&& Export(dataGridView, fileName, type);
}
//public static bool ExportToText(SaleInfo saleInfo, string fileName)
//{
// StreamWriter sw = new StreamWriter(fileName);
// //sw.WriteLine("" + saleInfo.
//}
static string GetSafeString(object obj)
{
return obj.ToString().Replace("<", "<").Replace(">", ">");
}
}
public enum FileType
{
Excel,
Html
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
public void ExportExcel(DataTable dtData, string filename)
{
System.Web.UI.WebControls.DataGrid dgExport = null;
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
if (dtData != null)
{
curContext.Response.Clear();
curContext.Response.Buffer = true;
DateTime now = new DateTime();
curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + this.Server.UrlEncode(filename + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xls"));
curContext.Response.ContentType = "application/vnd.ms-excel";
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
dgExport = new System.Web.UI.WebControls.DataGrid();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
dgExport.RenderControl(htmlWriter);
curContext.Response.Output.Write(strWriter.ToString());
curContext.Response.Flush();
curContext.Response.End();
}
}
将datagridview中的数据作为数据源传出函数即可 filename是你导出的文件名
{
System.Web.UI.WebControls.DataGrid dgExport = null;
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
if (dtData != null)
{
curContext.Response.Clear();
curContext.Response.Buffer = true;
DateTime now = new DateTime();
curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + this.Server.UrlEncode(filename + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xls"));
curContext.Response.ContentType = "application/vnd.ms-excel";
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
dgExport = new System.Web.UI.WebControls.DataGrid();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
dgExport.RenderControl(htmlWriter);
curContext.Response.Output.Write(strWriter.ToString());
curContext.Response.Flush();
curContext.Response.End();
}
}
将datagridview中的数据作为数据源传出函数即可 filename是你导出的文件名
追问
谢谢你帮我回答,但是我还是没有太明白。
我写的不是发到网上用的,而是一个课程设计,不知道“导出”按钮里的代码是什么?可以写一下具体步骤吗?
追答
我只是拷的一部分我之前的代码 导出EXcel大致的代码都相似
if (Request["action"] != null && Request["action"] == "export" && Common.IsInteger(Request["id"]))
{
DataTable dt = Common.ReadTable("select id as ID,Username as 申请人,sex as 性别 ,age as 年龄,telphone as 电话,email as 邮箱,resume as 简历,notes as 说明,addtime as 申请时间 from ED_MS_Offer where Employid=" + Request["id"].ToString());
string filename = Common.RecordSet("select job from ED_MS_Employ where id=" + Request["id"].ToString())[0];
ExportExcel(dt, filename);
}
这是我代码里调用导出方法前的相关代码
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
导出DateTable到Excel,如:
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.BufferOutput = true;
response.Cache.SetCacheability(HttpCacheability.Private); // 缓存使可以不保存就打开
response.Cache.SetExpires(DateTime.Now); // 立即过期
response.AppendHeader("Content-Type", "application/vnd.ms-excel");
response.AppendHeader("Content-Disposition", "attachment; filename =ProductClass.xls");
response.Write(@"<meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"">");
response.Write("<table border=\"1\" style=\"font-family: 宋体, Arial, sans-serif; font-size: 9.5pt;\">\r\n");
response.Write("<tr>");
response.Write("<th>厂商编码</th>");
response.Write("<th>厂商</th>");
response.Write("</tr>\r\n");
DataTable table = new DataTable();
//请在这里给table赋值,如果你的gridView绑定是table,可以试试这样:
//DataTable table = gridView.DataSource as Table;
foreach (DataRow row in table.Rows)
{
response.Write("<tr>");
response.Write(@"<td style='mso-number-format:\@;'>" + row["列名"].ToString() + "</td>");
response.Write("<td>" + row["列名"].ToString() + "</td>");
response.Write("</tr>");
}
}
response.Write("</table>\r\n");
response.Flush();
response.End();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.BufferOutput = true;
response.Cache.SetCacheability(HttpCacheability.Private); // 缓存使可以不保存就打开
response.Cache.SetExpires(DateTime.Now); // 立即过期
response.AppendHeader("Content-Type", "application/vnd.ms-excel");
response.AppendHeader("Content-Disposition", "attachment; filename =ProductClass.xls");
response.Write(@"<meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"">");
response.Write("<table border=\"1\" style=\"font-family: 宋体, Arial, sans-serif; font-size: 9.5pt;\">\r\n");
response.Write("<tr>");
response.Write("<th>厂商编码</th>");
response.Write("<th>厂商</th>");
response.Write("</tr>\r\n");
DataTable table = new DataTable();
//请在这里给table赋值,如果你的gridView绑定是table,可以试试这样:
//DataTable table = gridView.DataSource as Table;
foreach (DataRow row in table.Rows)
{
response.Write("<tr>");
response.Write(@"<td style='mso-number-format:\@;'>" + row["列名"].ToString() + "</td>");
response.Write("<td>" + row["列名"].ToString() + "</td>");
response.Write("</tr>");
}
}
response.Write("</table>\r\n");
response.Flush();
response.End();
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询