您的位置:首页 > 编程语言 > C#

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

2016-11-14 16:32 666 查看
其实想在datagridview中显示excel表格中的数据跟读取数据库中的数据没什么差别,只不过是创建数据库连接的时候连接字段稍有差别。

private void btnShow_Click(object sender, EventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();//首先根据打开文件对话框,选择excel表格
ofd.Filter = "表格|*.xls";//打开文件对话框筛选器
string strPath;//文件完整的路径名
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
strPath = ofd.FileName;
string strCon = "provider=microsoft.jet.oledb.4.0;data source=" + strPath + ";extended properties=excel 8.0";//关键是红色区域
OleDbConnection Con = new OleDbConnection(strCon);//建立连接
string strSql = "select * from [Sheet1$]";//表名的写法也应注意不同,对应的excel表为sheet1,在这里要在其后加美元符号$,并用中括号
OleDbCommand Cmd = new OleDbCommand(strSql, Con);//建立要执行的命令
OleDbDataAdapter da = new OleDbDataAdapter(Cmd);//建立数据适配器
DataSet ds = new DataSet();//新建数据集
da.Fill(ds, "shyman");//把数据适配器中的数据读到数据集中的一个表中(此处表名为shyman,可以任取表名)
//指定datagridview1的数据源为数据集ds的第一张表(也就是shyman表),也可以写ds.Table["shyman"]

       dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);//捕捉异常
}
}
}


运行结果如下:



2.导出DataGridView中的数据到Excel的方法:

public void ToExcel(DataGridView dataGridView1)
{
try
{
//没有数据的话就不往下执行
if (dataGridView1.Rows.Count == 0)
return;
//实例化一个Excel.Application对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

//让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写
excel.Visible = true;

//新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错
excel.Application.Workbooks.Add(true);
//生成Excel中列头名称
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
if (this.dataGridView1.Columns[i].Visible==true)
{
excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
}

}
//把DataGridView当前页的数据保存在Excel中
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
System.Windows.Forms.Application.DoEvents();
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if (this.dataGridView1.Columns[j].Visible==true)
{
if (dataGridView1[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + dataGridView1[j, i].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();
}
}

}
}

//设置禁止弹出保存和覆盖的询问提示框
excel.DisplayAlerts = false;
excel.AlertBeforeOverwriting = false;

//保存工作簿
excel.Application.Workbooks.Add(true).Save();
//保存excel文件
excel.Save("D:" + "\\KKHMD.xls");

//确保Excel进程关闭
excel.Quit();
excel = null;
GC.Collect();//如果不使用这条语句会导致excel进程无法正常退出,使用后正常退出
MessageBox.Show(this,"文件已经成功导出!","信息提示");

}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误提示");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: