c# 如何实现导出reogridcontrol中的数据到excel文件
1个回答
展开全部
代码如下:
1、创建form
public Form1()
{
InitializeComponent();
}
2、点击button开始查询db并导入excel数据
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cnn ; //sql连接对象
string connectionString = null; 数据库连接串
string sql = null; 执行sql定义
string data = null; 初始化结果
int i = 0;
int j = 0;
//以下是声明并创建excel文件
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//开始连接数据库
connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
cnn = new SqlConnection(connectionString);
cnn.Open(); //打开数据库
sql = "SELECT * FROM Product"; //定义查询sql语句
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn); //执行查询
DataSet ds = new DataSet();
dscmd.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
//数据导入到excel文件
1、创建form
public Form1()
{
InitializeComponent();
}
2、点击button开始查询db并导入excel数据
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cnn ; //sql连接对象
string connectionString = null; 数据库连接串
string sql = null; 执行sql定义
string data = null; 初始化结果
int i = 0;
int j = 0;
//以下是声明并创建excel文件
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//开始连接数据库
connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
cnn = new SqlConnection(connectionString);
cnn.Open(); //打开数据库
sql = "SELECT * FROM Product"; //定义查询sql语句
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn); //执行查询
DataSet ds = new DataSet();
dscmd.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
//数据导入到excel文件
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询