首页 新闻 搜索 专区 学院

Excel数据导入到DataGridView中

0
悬赏园豆:5 [已解决问题] 解决于 2011-06-14 11:00

如题,如何得到选择的一个Excel表,有数据的行数和列数

王元勋的主页 王元勋 | 菜鸟二级 | 园豆:413
提问于:2011-06-13 14:09
< >
分享
最佳答案
0

如果借助于SQL,就简单多了

否则,可以借助NPOI

收获园豆:5
邀月 | 高人七级 |园豆:25375 | 2011-06-13 14:17
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace Include_Office
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}

//导入Excel 按钮的点击事件
private void btnIncludeExcel_Click(object sender, EventArgs e)
{
IncludeExcelToDGV();
}

//读取Excel 将值显示在DataGridView中
public void IncludeExcelToDGV()
{
//这是一个客户端
Microsoft.Office.Interop.Excel.Application application;
//所有工作薄
Microsoft.Office.Interop.Excel.Workbooks workbooks;
//工作表
Microsoft.Office.Interop.Excel.Worksheet worksheet;
//所用到的工作表
Microsoft.Office.Interop.Excel.Workbook workbook;
string FileName;


OpenFileDialog file = new OpenFileDialog();
file.Filter = "文本文件(*.xls)|*.xls|所有文件(*.*)|*.*";
if (file.ShowDialog() == DialogResult.OK)
{
FileName = file.FileName;
application = new Microsoft.Office.Interop.Excel.Application();
workbooks = application.Workbooks;
workbook = returnworkbook(FileName, workbooks);
//选择第一个表
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];

//Range range = worksheet.Cells[1, 1] as Range; //这是选择第一行第1列的内容
//Range rangee = worksheet.Cells[1, 2] as Range; //这是第一行到2列的内容

System.Data.DataTable dt = new System.Data.DataTable();

//写入
王元勋 | 园豆:413 (菜鸟二级) | 2011-06-13 14:19
//for (int i = 1; i < worksheet.Rows.Count; i++)
//{
// dt.Rows = worksheet.Rows;
//}

//绑定数据源
this.dgvExcel.DataSource = null;
this.dgvExcel.DataSource = dt;

//退出关闭资源
workbook.Close(Type.Missing, FileName, Type.Missing);
workbooks.Close();
application.Quit();
}
}

//这里是打开一个工作表
private Workbook returnworkbook(string filename, Workbooks works)
{
Microsoft.Office.Interop.Excel.Workbook wk = works.Open(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
return wk;
}
}
}
但是中间的不知道这么写了,得不到那个Excel的行数和列数,不好循环
请教。。。
王元勋 | 园豆:413 (菜鸟二级) | 2011-06-13 14:21
请帮我贴出代码,分少的话我可以再加。。。。
王元勋 | 园豆:413 (菜鸟二级) | 2011-06-13 14:25
其他回答(3)
0

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;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btn_import_Click(object sender, EventArgs e)
    {
        //检查是否选中了文件
        if (!div_fu.HasFile)
        {
            lbl_messagebox.Text = "请选择文件再导入";
            lbl_messagebox.ForeColor = System.Drawing.Color.Red;
            lbl_messagebox.Visible = true;
            return;
        }
        //获取并保存上传的文件(临时保存)
        string strXLSFile = Server.MapPath("InfoExcel") + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xsl";
        div_fu.PostedFile.SaveAs(strXLSFile);


        //检查XLS数据的合法性,返回检查后的DataSet数据集
        DataSet ds = new DataSet();
        string strExceptionMessage = null;
        if (false == Check_XLS_Data_Validity(strXLSFile, out ds, out strExceptionMessage))
        {
            lbl_messagebox.Text = "导入未通过合法性检查<br/>" + strExceptionMessage;
            lbl_messagebox.ForeColor = System.Drawing.Color.Red;
            lbl_messagebox.Visible = true;
            System.IO.File.Delete(strXLSFile);
            return;
        }
      
        string strError;
        DataSet dsFinal = new DataSet();
        System.IO.File.Delete(strXLSFile);
        if (!ImportDsAssistTaskListToDataBase(ds, out strError))
        {
            Response.Write("<script>alert('导入出错," + strError + "');</script>");
            return;

        }
        else
        {
            Response.Write("<script>alert('项目批量导入成功!');</script>");
        }
        //删除上传的文件
        System.IO.File.Delete(strXLSFile);
        return;
    }

    protected bool Check_XLS_Data_Validity(string strXLSFile, out DataSet ds, out string strExceptionMessage)
    {
        //初始化输入
        ds = null;
        strExceptionMessage = null;
        //读取XLS文件
        string strConn = "provider=microsoft.jet.oledb.4.0;data source=" + strXLSFile + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
        OleDbConnection dbConn = new OleDbConnection(strConn);

        try
        {
            dbConn.Open();
        }
        catch (Exception ex)
        {
            strExceptionMessage = "错误:导入文件非期望的XLS,导入操作终止!" + ex.Message;
            return false;
        }
        DataTable dt = dbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        dbConn.Close();

        //默认打开第一张Sheet
        string sql = "select * from [" + dt.Rows[0][2].ToString().Trim() + "]";
        OleDbDataAdapter da = new OleDbDataAdapter(sql, dbConn);
        ds = new DataSet();
        try
        {
            da.Fill(ds);
        }
        catch (Exception ex)
        {
            strExceptionMessage = "错误:导入的XLS的文件中,Sheet表异常,操作终止!" + ex.Message;
            return false;
        }
        //检查相应的字段
        string sql1 = "";
        SqlDAL sqlAcess = new SqlDAL();
        DataSet ds1 = new DataSet();
        string Gname = "";
        if (ds.Tables[0].Rows.Count > 1)
        {

        }

        else
        {
            strExceptionMessage = "错误:导入的文件格式问题!导入操作终止";
            return false;
        }
        sqlAcess.Dispose();
        sqlAcess = null;
        //给列明添加名称
        foreach (DataColumn dc in ds.Tables[0].Columns)
     
            dc.ColumnName = ds.Tables[0].Rows[0][dc.Ordinal].ToString();


      
        //移除行标题
        ds.Tables[0].Rows.RemoveAt(0);
        strExceptionMessage = "检查数据成功!";
        return true;

    }

 

    private bool ImportDsAssistTaskListToDataBase(DataSet ds, out string strError)
    {

        string strTable = "SoftContact";
        strError = "";
        try
        {
            //数据批量导入SqlServer,创建实例
            SqlBulkCopy sqlbulk = new SqlBulkCopy(System.Configuration.ConfigurationManager.ConnectionStrings["db_CRPConnectionString"].ConnectionString);
            //目标数据库名
            sqlbulk.DestinationTableName = strTable;
            //数据集字段索引与数据库字段索引映射
            foreach (DataColumn dc in ds.Tables[0].Columns)
           
                sqlbulk.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);
           
            //导入
            sqlbulk.WriteToServer(ds.Tables[0]);
            sqlbulk.Close();
            return true;
        }
        catch (Exception ex)
        {
            strError = "错误原因:导入临时表异常,导入操作终止!" + ex.Message;
            return false;

        }
    }

}

 

 

自己看吧,很详细的

杀 手 | 园豆:213 (菜鸟二级) | 2011-06-13 15:13
我要的不是导出Excel,是给Excel文件内容导入到DataGridView中,谢谢了
支持(0) 反对(0) 王元勋 | 园豆:413 (菜鸟二级) | 2011-06-13 15:27
0

我说,你的要求和读取excel然后绑定到DataGridView中吧,这个你使用和access相似的读取就可以做到了。

或者使用 CYQ.Data 数据框架,做到这个就更简单了。

路过秋天 | 园豆:4763 (老鸟四级) | 2011-06-13 20:32
0
祝福灵魂 | 园豆:202 (菜鸟二级) | 2013-03-11 17:14
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册