gridview绑定excel(c#.net 中 如何将gridview中的数据导出到excel中)

本文目录
- c#.net 中 如何将gridview中的数据导出到excel中
- asp.net将Excel导入到gridview问题
- C# datagridview如何载入excel数据
- 如何将gridview的数据导出到EXCEL
- 如何excel导入gridview
- 如何将excel导入到数据库中并在gridview中显示
- gridview 导出excel 颜色问题
- 如何将包含自定义控件GridView导出到Excel
- 如何将数据绑到gridview然后导成excel
- C#中如何实现从 excel导入数据,并绑定到gridview上
c#.net 中 如何将gridview中的数据导出到excel中
// 导出列表信息到Excel
public static void gSendGridInfoToExcel(DataGrid GridX)
{
Excel.Application excel= new Excel.ApplicationClass();
Excel._Workbook xBk = excel.Workbooks.Add(true);
Excel._Worksheet xSt = (Excel._Worksheet)xBk.ActiveSheet;
Excel.Range excelCell=null;
try
{
//赋值对象
object objarr;
DataTable dtTest=new DataTable();;
int i,j;
int iRows,iCows;
int iVisable;
iVisable=0;
iCows=0;
ArrayList list=new ArrayList();
//如果绑定数据源是DataTable和DataSet,取得行数
if (GridX.DataSource is System.Data.DataSet || GridX.DataSource is System.Data.DataTable)
{
dtTest=(DataTable)GridX.DataSource;
iRows=dtTest.Rows.Count;
}
else if (GridX.DataSource is System.Data.DataView)
{
DataView dvTest=(DataView)GridX.DataSource;
iRows=dvTest.Count;
dtTest=dvTest.Table;
}
//如果是集合取得行数
else
{
System.Collections.CollectionBase ColTest;
ColTest=(System.Collections.CollectionBase)GridX.DataSource;
iRows=ColTest.Count;
}
//如果有TableStyles则根据TableStyles取得(标题行)
if (GridX.TableStyles.Count》0)
{
iCows=GridX.TableStyles.GridColumnStyles.Count;
for(i=0;i《iCows;i++)
{
if(GridX.TableStyles.Width》0)
{
iVisable++;
list.Add(GridX.TableStyles.HeaderText);
}
}
objarr = new object;
objarr=list.ToArray();
excelCell = xSt.get_Range(excel.Cells);
excelCell.Value2 = objarr;
//数据行
for(i=0;i《iRows;i++)
{
objarr = new object;
list.Clear();
for(j=0;j《iCows;j++)
{
if(GridX.TableStyles.Width》0)
{
list.Add("’"+GridX.ToString().Replace("\n",""));
}
}
if (list.Equals(System.DBNull.Value))
{
break;
}
objarr=list.ToArray();
excelCell = xSt.get_Range(excel.Cells);
excelCell.Value2 = objarr;
}
}
else
{
iCows=dtTest.Columns.Count;
for(i=0;i《iCows;i++)
{
list.Add(dtTest.Columns.Caption);
}
objarr = new object;
objarr=list.ToArray();
excelCell = xSt.get_Range(excel.Cells);
excelCell.Value2 = objarr;
//数据行
for(i=0;i《iRows;i++)
{
objarr = new object;
list.Clear();
for(j=0;j《iCows;j++)
{
list.Add("’"+GridX.ToString().Replace("\n",""));
}
if (list.Equals(System.DBNull.Value))
{
break;
}
objarr=list.ToArray();
excelCell = xSt.get_Range(excel.Cells);
excelCell.Value2 = objarr;
}
}
dtTest.Dispose();
excel.Visible=true;
}
catch (System.Exception e)
{
throw e;
}
finally
{
excelCell=null;
xBk=null;
xSt=null;
excel=null;
GC.Collect();
}
}
}
asp.net将Excel导入到gridview问题
/// 《summary》 /// 导入数据到GridView
/// 《/summary》
/// 《param name="fileUpload"》文件上传控件对象《/param》
/// 《param name="filePath"》要存放文件的服务器路径《/param》
/// 《param name="gridview"》目标GridView《/param》
/// 《param name="keyColIndex"》用于导入的主键列《/param》
/// 《returns》返回没有导入的数据DataSet《/returns》
public static DataSet ExcelToGridView(FileUpload fileUpload, string filePath, GridView gridview, int keyColIndex, string strMsg)
{
string errMsg = string.Empty;
DataSet ds = null ;
try
{
if ( ! filePath.EndsWith("\\"))
{
filePath += "\\";
}
string fileName = fileUpload.FileName.Replace(".xls", "") + "_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
string fullFileName = filePath + fileName;
fileUpload.SaveAs(fullFileName);
ds = ExcelToGridView(fullFileName, gridview, keyColIndex,errMsg);
if ( errMsg != string.Empty)
{
errMsg += "将数据导入GridView失败." + errMsg ;
};
}
catch (Exception ex)
{
errMsg += "上传excel文件失败." ;
}
strMsg = errMsg;
return ds ;
}
以上为 数据导入的方法 然后你可以绑定到你的 GridView 上面就OK了 如果还有什么问题 请来信息QQ:372114189
C# datagridview如何载入excel数据
dataGridView1.DataSource = ds.Tables;
一直绑定ds得excel表,如果你新数据还是放到相同名字的table里面,可能会出现类型不一致
datagridview.datasource=Null;
清空后,就相当于重新开始
如果想知道哪里提示类型不匹配,你得把加载Excel代码拿出来
如何将gridview的数据导出到EXCEL
给你个思路,分页的话,在导出时先关闭分页,绑数据,导出后,再打开分页
方法1简单:
public void ToExcel()//整个GRIDVIEW导出到EXCEL
{
string filename="数据表" + DateTime.Now.ToString("yyyyMMdd") + ".xls";
string style = @"《style》 .text { mso-number-format:\@; } 《/script》 "; //解决第一位字符为零时不显示的问题
this.GridView1.AllowPaging = false;//关闭分页
this.GridView1.DataBind();//绑定数据
filename = HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);//解决导出EXCEL时文件名为汉字时乱码的问题
Response.ClearContent;
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/excel";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
System.IO.StringWriter sw = new System.IO.StringWriter();//定义一个字符串写入对象
HtmlTextWriter htw = new HtmlTextWriter(sw);//将html写到服务器控件输出流
this.GridView1.RenderControl(htw);//将控件GRIDVIEW中的内容输出到HTW中
Response.Write(style);
Response.Write(sw);
Response.End();
this.GridView1.AllowPaging = true;
}
***隐藏网址***
如何excel导入gridview
参考下面部分代码
//打开对话框 并且选择 Excel文件
string FileName = "";
openFileDialog1.Filter = "Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Title = "打开文件";
openFileDialog1.InitialDirectory = System.Windows.Forms.Application.StartupPath;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ShowDialog();
FileName = openFileDialog1.FileName;
textBox1.Text = FileName;
//Excel数据导入
if (ds != null && ds.Tables.Contains("岗位工资表"))
{
ds.Tables.Clear();
}
try
{
string MyExcel = this.textBox1.Text;
string Mysheet = "Sheet1";
//这里跟连接数据库差不多
string str = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + MyExcel + ";Excel 8.0;HDR=YES";
OleDbConnection Myconnect = new OleDbConnection(str);
string MySQL = "select * from ";
//string MySQL = "select * from 岗位工资表";
OleDbCommand Mycommand = new OleDbCommand(MySQL, Myconnect);
OleDbDataAdapter Myadapter = new OleDbDataAdapter(Mycommand);
Myadapter.Fill(ds, "岗位工资表");
this.GridView1.DataSource = ds.Tables;
}
catch (Exception)
{
//throw;
}
label3.Text = "Excel中的岗位信息:";
this.btnSave.Enabled = true;
this.btnCancel.Enabled = true;
如何将excel导入到数据库中并在gridview中显示
参考代码如下:
把Excel中的数据导入gridView显示,再导入数据库
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
//创建一个临时DataTable,为了把Excel中的数据导入gridView后再导入数据库。
private static DataTable dtTemp;
/// 《summary》
/// 把Excel导入Gridview,首先把文件上传到服务器
/// 《/summary》
/// 《param name="sender"》《/param》
/// 《param name="e"》《/param》
protected void btnImport_Click(object sender, EventArgs e)
{
//导入Excel文件
//检查文件是否存在
//HasFile用来检查上传文件控件FileUpload是否有指定文件
if (FileUpload1.HasFile == false)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "《script language=’javascript’ defer》alert(’请您选择Excel文件! ’);《/script》");
return;//当无文件时,返回
}
string filename = DateTime.Now.ToString("yyyymmddhhMMss") + FileUpload1.FileName;
//获取Execle文件名 DateTime日期函数
string savePath = Server.MapPath(("../Doc/") + filename);//Server.MapPath 获得虚拟服务器相对路径
//如果已经存在就清空
ClearFile(Server.MapPath("../Doc/"));
FileUpload1.SaveAs(savePath); //SaveAs 将上传的文件内容保存在服务器上
DataTable dt = createDataSource(savePath);
if (dtTemp == null)
{
dtTemp = new DataTable();
dtTemp = dt;
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
/// 《summary》
/// 从gridview导入数据库
/// 《/summary》
/// 《param name="sender"》《/param》
/// 《param name="e"》《/param》
protected void btnSubmit_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = dtTemp;
for (int i = 0; i 《 dt.Rows.Count; i++)
{
//导入数据库的代码省略
}
Response.Write("《script》alert(’添加成功!!’)《/script》");
}
/// 《summary》
/// 将路径下的Excel文件转换为DataTable类型的数据源
/// 《/summary》
/// 《param name="strPath"》Excel路径《/param》
/// 《returns》《/returns》
private DataTable createDataSource(string strPath)
{
string strCon;
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties=Excel 8.0";
OleDbConnection con = new OleDbConnection(strCon);
OleDbDataAdapter da = new OleDbDataAdapter("select * from ", con);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
/// 《summary》
/// 将Excel文件暂存到服务器端的一个文件夹中,用这个方法删除掉
/// 《/summary》
/// 《param name="FilePath"》Excel路径《/param》
private void ClearFile(string FilePath)
{
String files = System.IO.Directory.GetFiles(FilePath);
if (files.Length 》 5)
{
for (int i = 0; i 《 5; i++)
{
try
{
System.IO.File.Delete(files);
}
catch
{
}
}
}
}
gridview 导出excel 颜色问题
不知道你说的是字体颜色还是单元格填充色。
如果你说的软件中不能设置,也可以在EXCEL中设置。
如果指的是填充色,导出后,在EXCEL中,按CTRL+A全选当前表,再在工具中的填充颜色按钮中点选一下“无填充色”就行了。
如果是指字体颜色,按上面操作后,点工具工具栏上“字体颜色”中的“自动”就行了。
如何将包含自定义控件GridView导出到Excel
实现导出GridView到Excel的步骤:
步骤1 : 将C1GridView绑定至数据源
步骤2 : 导出C1GridView至Excel
导出到Excel需要分成两步。首先是将GridView保存至一个HTML字符串,然后将该HtmlTextWriter对象输出到一个StringWriter 对象。
具体的代码实现,请参考下面的博客
***隐藏网址***
如何将数据绑到gridview然后导成excel
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data .SqlClient ;
using System.Data ;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String sqlconn = "Server=.; DataBase=db; Integrated Security=SSPI ";
string sql = "select top 10 * from table";
SqlConnection myConnection = new SqlConnection(sqlconn);// 创建数据库连接实例
myConnection.Open(); //打开数据库
SqlCommand myCommand = new SqlCommand(sql, myConnection);//创建sql的实例,执行一个sql
SqlDataAdapter Adapter = new SqlDataAdapter();//创建一个sql数据适配器
Adapter.SelectCommand = myCommand;//属性设置为 从数据源中检索记录
DataSet myDs = new DataSet(); //创建数据集实例
Adapter.Fill(myDs);//填充数据集
GridView1.DataSource = myDs.Tables.DefaultView;//
GridView1.DataBind();
// DataToExcel("测试的cxcel", GridView1);
myConnection.Close();//关闭数据库连接
}
public void DataToExcel(string fileName, GridView myGridView)
{
//定义文档类型、字符编码
Response.Clear();
Response.Buffer = false;
//Response.Charset = "utf-8";
Response.Charset = "GB2312";
//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
//filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc || .xls || .txt ||.htm
Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
//Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//Response.ContentType指定文件类型 可以为application/ms-excel || application/ms-word || application/ms-txt || application/ms-html || 或其他浏览器可直接支持文档
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
//System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
//定义一个输入流
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
//将目标数据绑定到输入流输出
myGridView.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
//下面这个空语句一定要加,否则会出现“必须放在具有 runat=server 的窗体标记内。”的错误
public override void VerifyRenderingInServerForm(Control control)
{
}
//点击事件,生成excel
protected void Button1_Click(object sender, EventArgs e)
{
DataToExcel("测试的cxcel", GridView1);
}
}
C#中如何实现从 excel导入数据,并绑定到gridview上
我的例子在Windows应用程序(C#)上经过了测试:
string xlsFilePath = "G:\\Book1.xls";
string connectionString;
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsFilePath + ";Extended Properties=’Excel 8.0;HDR=False;IMEX=1’";
OleDbConnection conn = new OleDbConnection(connectionString);
String strQuery = "SELECT * FROM "; //可以更改工作表名称
OleDbDataAdapter da = new OleDbDataAdapter(strQuery, conn);
DataSet ds = new DataSet();
da.Fill(ds, "Sheet1");
DataTable dt = ds.Tables;
dataGridView1.DataSource = dt;
conn.Close();
运行效果:

更多文章:
export用法搭配(export后用介词in还是from)
2026年2月27日 23:30
i wrote python(python零基础自学的基本知识)
2025年10月1日 20:00
java框架实现日志管理的原理步骤(java中如何使用log4j将记录的操作日志信息)
2025年9月7日 10:15
int是什么意思啊音响上(汽车CD机上的英文字母各是什么意思)
2026年9月13日 08:45
completed是什么意思中文(level completed什么意思)
2026年1月3日 20:15
python读取文件相对路径(python中的绝对路径和相对路径均如何理解呢)
2025年10月1日 15:45
郑州cms建站系统(国内的JAVA版CMS系统哪些比较给力)
2025年9月10日 06:45
正则表达式过滤1234(如何用正则表达式过滤除数字以外的其他字符)
2026年2月16日 12:30
用python画简单的花(pythoncircle函数画花瓣怎么计算角度)
2026年9月25日 13:15
phpstorm如何配置服务器(phpstorm 怎么设置http代理服务器)
2026年1月27日 20:00
sql ser数据库安装路径(我的SQL server 2000安装在c盘下,那么以后保存的数据库都是默认存在c盘下了,)
2025年11月2日 04:45








![grep使用正则表达式(正则表达式:grep “^[[:space :]]*$” 表示什么)](/static/images/nopic/30.jpg)



