C#中把datagridview中显示的数据导出到excel中

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#中把datagridview中显示的数据导出到excel中相关的知识,希望对你有一定的参考价值。

本人用的是LINQ写的,想要用一个按钮实现datagridview中的数据的导出到excel,不知道怎么写,请教高人写下具体步骤和代码,不胜感激!

参考技术A 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
参考技术B 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是你导出的文件名追问

谢谢你帮我回答,但是我还是没有太明白。
我写的不是发到网上用的,而是一个课程设计,不知道“导出”按钮里的代码是什么?可以写一下具体步骤吗?

追答

我只是拷的一部分我之前的代码 导出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);

这是我代码里调用导出方法前的相关代码

本回答被提问者采纳
参考技术C 导出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();

如何将datagridview导出到Open Office Excel c#

【中文标题】如何将datagridview导出到Open Office Excel c#【英文标题】:How to export datagridview into Open Office Excel c# 【发布时间】:2014-12-17 07:20:27 【问题描述】:

我有一个 datagridview,我可以将它导出到 Microsoft Excel。现在我想将 datagridview 导出到 Open Office Excel。我不知道在我的 Open Office 项目中要使用哪些程序集作为参考。对于 Microsoft Excel,我使用了以下参考,后跟事件代码。

using Excel=Microsoft.Office.Interop.Excel;


private void exportToMSExcelToolStripMenuItem_Click(object sender, EventArgs e)
        
            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 = "Exported from .net app";
                for (int i = 1; i < datagridEC.Columns.Count + 1; i++)
                
                    worksheet.Cells[1, i] = datagridEC.Columns[i - 1].HeaderText;
                
                for (int i = 0; i < datagridEC.Rows.Count; i++)
                
                    for (int j = 0; j < datagridEC.Columns.Count; j++)
                    
                        worksheet.Cells[i + 2, j + 1] = datagridEC.Rows[i].Cells[j].Value.ToString();
                    
                

            
            catch (Exception ex)
            
                MessageBox.Show("ERROR--> " + ex.Message.ToString(), "ERROR");
            
            finally
            
            
        

这适用于 Microsoft Office,但现在我想将其替换为 Open Office Excel。

【问题讨论】:

此文件应该适用于 Open Office。使用 Open Office 打开时出现什么错误? 【参考方案1】:

您需要为以下汇编添加引用:cli_basetype、cli_cppihelper、cli_oootypes、cli_ure、cli_uretypes

还有

using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.bridge;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.beans;
using UNO = unoidl.com.sun.star.uno;
using OOo = unoidl.com.sun.star;
using unoidl.com.sun.star.text;
using unoidl.com.sun.star.container;
using unoidl.com.sun.star.sheet;
using unoidl.com.sun.star.table;

以及如何获取工作表的示例:

            UNO.XComponentContext context = uno.util.Bootstrap.bootstrap();
            XMultiServiceFactory SrvManager = (XMultiServiceFactory)context.getServiceManager();
            XComponentLoader loader = (XComponentLoader)SrvManager.createInstance("com.sun.star.frame.Desktop");

            string AFile = "file:///" + "filePath";

            PropertyValue[] props = new PropertyValue[0];

            XComponent oDoc = loader.loadComponentFromURL(AFile, "_blank", 0, props);

            XSpreadsheetDocument xSpreadDoc = (XSpreadsheetDocument)oDoc;

            XSpreadsheets xSheets = xSpreadDoc.getSheets();
            XIndexAccess xIA = (XIndexAccess)xSheets;

            XSpreadsheet xSheet = (XSpreadsheet)xIA.getByIndex(0).Value;

【讨论】:

谢谢@Gleb。我得到了它。但我有一个关于程序集的问题。如何添加它们?

以上是关于C#中把datagridview中显示的数据导出到excel中的主要内容,如果未能解决你的问题,请参考以下文章

C#读取Excel表格数据到DataGridView中和导出DataGridView中的数据到Excel

c# winform DataGridView导出数据到Excel中,可以导出当前页和全部数据

c#中将datagridview中数据导出到excel中,点击保存可以保存,点击取消就出

在C#中,如何把DataGridview中的数据导出到一个Excel表中

c# winform下如何实现datagridview拆分单元格或者跨行显示

C# 中的 DataGridView 导出器