c#怎么对DataGrid实现导入导出功能??? 导入导出的格式为Excel的格式,大侠们啊,求救啊~~ 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 给你一个导出的例子:/// <summary> /// 打开Excel并将DataGridView控件中数据导出到Excel /// </summary> /// <param name="dgv">DataGridView对象 </param> /// <param name="isShowExcle">是否显示Excel界面 </param> /// <res> /// add com "Microsoft Excel 11.0 Object Library" /// using Excel=Microsoft.Office.Interop.Excel; /// </res> /// <returns> </returns> public bool DataGridviewShowToExcel(DataGridView dgv, bool isShowExcle) { if (dgv.Rows.Count == 0) return false; //建立Excel对象 Excel.Application excel = new Excel.Application(); excel.Application.Workbooks.Add(true); excel.Visible = isShowExcle; //生成字段名称 for (int i = 0; i < dgv.ColumnCount; i++) { excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText; } //填充数据 for (int i = 0; i < dgv.RowCount - 1; i++) { for (int j = 0; j < dgv.ColumnCount; j++) { if (dgv[j, i].ValueType == typeof(string)) { excel.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString(); } else { excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString(); } } } return true; } 可以先将DataGrid中的内容导出到一个临时的文本文件中,然后调用Microsoft.Office.Interop.Excel程序集完成文本导入Excel的功能,CodeProject上面有一个文章,你可以参考:Microsoft.Office.Interop.Excel 提供一个实例,你参考下就可以了,希望对你有用处 /// <summary> /// 实现导出到execl文件 /// </summary> /// <param name="filePathName">保存的文件路径和名称</param> /// <param name="GVPassDetail">GridView控件的数据</param> public void ExportDataToCSV(string filePathName, GridView GVPassDetail) { using (FileStream fileStream = new FileStream(filePathName, FileMode.CreateNew, FileAccess.ReadWrite)) { StringBuilder stringBuilder = new StringBuilder(); using (StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.Default)) { int colCount = GVPassDetail.Columns.Count; for (int i = 0; i < colCount; i++) { stringBuilder.Append(GVPassDetail.Columns[i].HeaderText); if (i < colCount - 1) { stringBuilder.Append(","); } } stringBuilder.Append("\n"); //换行 for (int i = 0; i < GVPassDetail.Rows.Count; i++) { for (int j = 0; j < GVPassDetail.Columns.Count; j++) { stringBuilder.Append(GVPassDetail.Rows[i].Cells[j].Text.Trim()); if (j < GVPassDetail.Columns.Count - 1) { stringBuilder.Append(","); } } stringBuilder.Append("\n"); } streamWriter.Write(stringBuilder.ToString()); streamWriter.Close(); } } } 不好意思,忘记附上文章地址了:导出DataGrid数据到Excel的文章地址:http://www.codeproject.com/KB/cs/export2excel.aspxhttp://www.codeproject.com/KB/office/export.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridviewExportExcel.aspx.cs" Inherits="GridviewExcel" EnableEventValidation="false" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Gridview Excel</title> </head><body> <form id="form1" runat="server"> <div id="container"> <asp:GridView ID="GridView1" BorderColor="Black" OnRowDataBound="GridView1_RowDataBound" runat="server" AutoGenerateColumns="False" Font-Size="12px" Width="530px" AllowSorting="True"> <Columns> <asp:BoundField DataField="EmpID" HeaderText="编号" /> <asp:BoundField DataField="EmpRealName" HeaderText="姓名" /> <asp:BoundField DataField="EmpSex" HeaderText="性别" /> <asp:BoundField DataField="EmpAddress" HeaderText="住址" /> </Columns> <HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" /> <RowStyle HorizontalAlign="Center" /> <PagerStyle HorizontalAlign="Center" /> </asp:GridView> <asp:Button ID="Button1" runat="server" Text="导 出 EXCEL 表 格" Height="34px" OnClick="Button1_Click" Width="263px" /> <asp:Button ID="Button2" runat="server" Text="导 出 Word 文 档" Height="34px" OnClick="Button2_Click" Width="263px" /></div> </form></body></html>using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Drawing;using System.IO;using System.Text;/// <summary>/// Author:匆匆 Blog:http://www.cnblogs.com/huangjianhuakarl//// 将Gridview中的数据导出Excel表格/// </summary>public partial class GridviewExcel : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { bind(); } } /// <summary> /// 数据绑定 /// </summary> public void bind() { string sqlStr = "select * from Employee"; DataSet myds = Common.dataSet(sqlStr); GridView1.DataSource = myds; GridView1.DataKeyNames = new string[] { "ID" }; GridView1.DataBind(); } /// <summary> /// 在 GridView 控件中的某个行被绑定到一个数据记录时发生。此事件通常用于在某个行被绑定到数据时修改该行的内容。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { foreach (TableCell tc in e.Row.Cells) { tc.Attributes["style"] = "border-color:Black"; } if (e.Row.RowIndex != -1) { int id = GridView1.PageIndex * GridView1.PageSize + e.Row.RowIndex + 1; e.Row.Cells[0].Text = id.ToString(); } } /// <summary> /// 导出Excel /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button1_Click(object sender, EventArgs e) { Export("application/ms-excel", "Employee information.xls"); } /// <summary> /// 定义导出Excel的函数 /// </summary> /// <param name="FileType"></param> /// <param name="FileName"></param> private void Export(string FileType, string FileName) { Response.Charset = "GB2312"; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString()); Response.ContentType = FileType; this.EnableViewState = false; StringWriter tw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); GridView1.RenderControl(hw); Response.Write(tw.ToString()); Response.End(); } /// <summary> /// 此方法必重写,否则会出错 /// </summary> /// <param name="control"></param> public override void VerifyRenderingInServerForm(Control control) { } protected void Button2_Click(object sender, EventArgs e) { //Export("application/ms-excel", "Employee.doc"); Export("application/ms-word", "员工信息.doc");//都可以 }} private DataSet createDataSource() { string strCon; strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/Files/Employee.xls") + ";Extended Properties=Excel 8.0;"; OleDbConnection con = new OleDbConnection(strCon); OleDbDataAdapter da = new OleDbDataAdapter("select * from [Employee$]", con); DataSet ds = new DataSet(); da.Fill(ds); return ds; } 就是把EXCEL当数据库读取到dataset数据表里 try { OpenFileDialog openFile = new OpenFileDialog();//打开文件对话框。 openFile.Filter = ("Excel 文件(*.xls)|*.xls");//后缀名。 if (openFile.ShowDialog() == DialogResult.OK) { string filename = openFile.FileName; int index = filename.LastIndexOf("\\");//截取文件的名字 filename = filename.Substring(index + 1); //conExcel.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + // Application.StartupPath + "\\Appdata.mdb"; //将excel导入access //distinct :删除excel重复的行. //[excel名].[sheet名] 已有的excel的表要加$ //where not in : 插入不重复的记录。 string sql = "insert into S_Course select distinct * from [Excel 8.0;database=" + filename + "].[sheet1$] where Cno not in (select Cno from S_Course) "; DataBase db = new DataBase(); if (db.UpdateDB(sql)) { MessageBox.Show("导入数据成功", "导入数据", MessageBoxButtons.OK, MessageBoxIcon.Information); } else {MessageBox.Show("导入失败!","提示",MessageBoxButtons.OK,MessageBoxIcon.Error);} } } catch (Exception ex) { MessageBox.Show(ex.ToString()); }我这样弄为什么有一个字段导入数字不行,只能导入字符串类型的 c#中 怎样输出2个连着的双引号 datatable 多次赋值还是声明多个datatable 初学C#学晕了,有问题请大家帮忙(在线等) 0行0列 未将对象引用设置到对象的实例 求指导 急用,请高手指点 请问如何讲dataview作为水晶报表的数据源 用過 Baan 系統的請進! 如何控制文本框只能输入数字 有关DLL的调用。。我如何调用这个方法啊。。。特别是里边的参数我不会写?? 求问:如何得到系统抛出的例外的类型 电子标签技术! 请问如何自动生成表中的编号
/// 打开Excel并将DataGridView控件中数据导出到Excel
/// </summary>
/// <param name="dgv">DataGridView对象 </param>
/// <param name="isShowExcle">是否显示Excel界面 </param>
/// <res>
/// add com "Microsoft Excel 11.0 Object Library"
/// using Excel=Microsoft.Office.Interop.Excel;
/// </res>
/// <returns> </returns>
public bool DataGridviewShowToExcel(DataGridView dgv, bool isShowExcle)
{
if (dgv.Rows.Count == 0)
return false;
//建立Excel对象
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = isShowExcle;
//生成字段名称
for (int i = 0; i < dgv.ColumnCount; i++)
{
excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < dgv.RowCount - 1; i++)
{
for (int j = 0; j < dgv.ColumnCount; j++)
{
if (dgv[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString();
}
}
}
return true;
}
Microsoft.Office.Interop.Excel
/// 实现导出到execl文件
/// </summary>
/// <param name="filePathName">保存的文件路径和名称</param>
/// <param name="GVPassDetail">GridView控件的数据</param>
public void ExportDataToCSV(string filePathName, GridView GVPassDetail)
{
using (FileStream fileStream = new FileStream(filePathName, FileMode.CreateNew, FileAccess.ReadWrite))
{
StringBuilder stringBuilder = new StringBuilder();
using (StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.Default))
{
int colCount = GVPassDetail.Columns.Count; for (int i = 0; i < colCount; i++)
{
stringBuilder.Append(GVPassDetail.Columns[i].HeaderText);
if (i < colCount - 1)
{
stringBuilder.Append(",");
}
}
stringBuilder.Append("\n"); //换行 for (int i = 0; i < GVPassDetail.Rows.Count; i++)
{
for (int j = 0; j < GVPassDetail.Columns.Count; j++)
{
stringBuilder.Append(GVPassDetail.Rows[i].Cells[j].Text.Trim());
if (j < GVPassDetail.Columns.Count - 1)
{
stringBuilder.Append(",");
}
}
stringBuilder.Append("\n");
}
streamWriter.Write(stringBuilder.ToString());
streamWriter.Close(); }
}
}
导出DataGrid数据到Excel的文章地址:
http://www.codeproject.com/KB/cs/export2excel.aspx
http://www.codeproject.com/KB/office/export.aspx
<head runat="server">
<title>Gridview Excel</title>
</head>
<body>
<form id="form1" runat="server">
<div id="container">
<asp:GridView ID="GridView1" BorderColor="Black" OnRowDataBound="GridView1_RowDataBound" runat="server" AutoGenerateColumns="False" Font-Size="12px" Width="530px" AllowSorting="True">
<Columns>
<asp:BoundField DataField="EmpID" HeaderText="编号" />
<asp:BoundField DataField="EmpRealName" HeaderText="姓名" />
<asp:BoundField DataField="EmpSex" HeaderText="性别" />
<asp:BoundField DataField="EmpAddress" HeaderText="住址" />
</Columns>
<HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" />
<RowStyle HorizontalAlign="Center" />
<PagerStyle HorizontalAlign="Center" />
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="导 出 EXCEL 表 格" Height="34px" OnClick="Button1_Click" Width="263px" />
<asp:Button ID="Button2" runat="server" Text="导 出 Word 文 档" Height="34px" OnClick="Button2_Click" Width="263px" /></div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.IO;
using System.Text;
/// <summary>
/// Author:匆匆 Blog:http://www.cnblogs.com/huangjianhuakarl/
/// 将Gridview中的数据导出Excel表格
/// </summary>
public partial class GridviewExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}
/// <summary>
/// 数据绑定
/// </summary>
public void bind()
{
string sqlStr = "select * from Employee";
DataSet myds = Common.dataSet(sqlStr);
GridView1.DataSource = myds;
GridView1.DataKeyNames = new string[] { "ID" };
GridView1.DataBind();
}
/// <summary>
/// 在 GridView 控件中的某个行被绑定到一个数据记录时发生。此事件通常用于在某个行被绑定到数据时修改该行的内容。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (TableCell tc in e.Row.Cells)
{
tc.Attributes["style"] = "border-color:Black";
}
if (e.Row.RowIndex != -1)
{
int id = GridView1.PageIndex * GridView1.PageSize + e.Row.RowIndex + 1;
e.Row.Cells[0].Text = id.ToString();
}
}
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
Export("application/ms-excel", "Employee information.xls");
}
/// <summary>
/// 定义导出Excel的函数
/// </summary>
/// <param name="FileType"></param>
/// <param name="FileName"></param>
private void Export(string FileType, string FileName)
{
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
/// <summary>
/// 此方法必重写,否则会出错
/// </summary>
/// <param name="control"></param>
public override void VerifyRenderingInServerForm(Control control)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
//Export("application/ms-excel", "Employee.doc");
Export("application/ms-word", "员工信息.doc");//都可以
}
}
{
string strCon;
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/Files/Employee.xls") + ";Extended Properties=Excel 8.0;";
OleDbConnection con = new OleDbConnection(strCon);
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Employee$]", con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
{
OpenFileDialog openFile = new OpenFileDialog();//打开文件对话框。
openFile.Filter = ("Excel 文件(*.xls)|*.xls");//后缀名。
if (openFile.ShowDialog() == DialogResult.OK)
{
string filename = openFile.FileName;
int index = filename.LastIndexOf("\\");//截取文件的名字
filename = filename.Substring(index + 1);
//conExcel.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" +
// Application.StartupPath + "\\Appdata.mdb";
//将excel导入access
//distinct :删除excel重复的行.
//[excel名].[sheet名] 已有的excel的表要加$
//where not in : 插入不重复的记录。 string sql = "insert into S_Course select distinct * from [Excel 8.0;database=" +
filename + "].[sheet1$] where Cno not in (select Cno from S_Course) ";
DataBase db = new DataBase();
if (db.UpdateDB(sql))
{ MessageBox.Show("导入数据成功", "导入数据", MessageBoxButtons.OK, MessageBoxIcon.Information); }
else
{MessageBox.Show("导入失败!","提示",MessageBoxButtons.OK,MessageBoxIcon.Error);}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
我这样弄为什么有一个字段导入数字不行,只能导入字符串类型的