EXCLE显示在DataGridView,然后导入到SQL表中
大概是这样,现在有个EXCLE文件,我新建了winform 里面就一个DataGridView和 一个浏览一个导入按钮,现在我能做到的操作是 在ds能看到我找到的EXCLE ,在浏览按钮的时候,选择文件后,在DataGridView中显示出来数据,然后按导入按钮时候,就插入到SQL表中。代码在下面了,可是不知道如何显示到DATAGRIDVIEW ,并且我的 SQL表 都设计好了字段名称的,要一一对应,然后咧,EXCLE里是列 我想导入到SQL中变成行。 这个怎么操作呢?麻烦耐心看完,谢谢。~
public partial class SetDataImport : Office2007Form
{
public SetDataImport()
{
InitializeComponent();
}
public DataSet ImportExcel(string fileName)
{
// 判断是否有Excel
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
if (xlApp == null)
{
MessageBoxEx.Show("无法创建Excel对象,可能您的计算机未安装Excel");
return null;
}
//判断文件是否被其他进程使用
Microsoft.Office.Interop.Excel.Workbook workbook;
try
{
workbook = xlApp.Workbooks.Open(fileName, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, 1, 0);
}
catch
{
MessageBoxEx.Show("Excel文件处于打开状态,请保存关闭");
return null;
}
// 取得所有的sheet名称
int n = workbook.Worksheets.Count;
string[] SheetSet = new string[n];
System.Collections.ArrayList al = new System.Collections.ArrayList();
for (int i = 1; i <= n; i++)
{
SheetSet[i - 1] = ((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[i]).Name;
}
//释放Excel相关对象
workbook.Close(null, null, null);
xlApp.Quit();
if (workbook != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
}
if (xlApp != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
}
GC.Collect();
//把EXCEL导入到DataSet
DataSet ds = new DataSet();
string connStr = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + fileName + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
OleDbDataAdapter da;
for (int i = 1; i <= n; i++)
{
string sql = "select * from [" + SheetSet[i - 1] + "$] ";
da = new OleDbDataAdapter(sql, conn);
da.Fill(ds, SheetSet[i - 1]);
da.Dispose();
}
conn.Close();
conn.Dispose();
}
return ds;
}
private void btn_lead_Click(object sender, EventArgs e)
{
}
private void btn_browse_Click(object sender, EventArgs e)
{