zoukankan      html  css  js  c++  java
  • C#读取Excel导入到数据库及读取Excel工作表为任意表名的方法

    添加openFileDialog1,用于选择Excel表

    using System.IO;
    using System.Data.OleDb;

    //导入Excel表
    private void btnInto_Click(object sender, EventArgs e)
    {

    string resultFile = "";
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Filter = "表格文件(*.xls,*.xlsx)|*.xls;*.xlsx";
    openFileDialog1.FilterIndex = 2;
    openFileDialog1.RestoreDirectory = true;
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
    resultFile = openFileDialog1.FileName;

    GetExcel(resultFile);

    }
    }
    /// <summary>
    /// 获取Excel表格内容
    /// </summary>
    /// <param name="fileName">Excel表名字</param>
    private void GetExcel(string fileName)
    {

    根据表名创建链接字符串
    string excelStr = "Provider= Microsoft.Ace.OleDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";

    string strSheetName = GetExcelFirstTableName(fileName);//获取第一个工作表名字
    if (strSheetName!=null)
    {

    DataTable dt = new DataTable();

    using (System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter("select * from[" + strSheetName + "]", excelStr))
    {
    try
    {
    myCommand.Fill(dt);

    }
    catch (Exception ex)
    {

    MessageBox.Show("操作失败" + ex.Message);
    }

    }
    dgvShow.DataSource = dt;


    }
    else
    {
    MessageBox.Show("这是张空表!");
    }

    }


    /// <summary>
    /// 获取excel第一个工作表名字
    /// </summary>
    /// <param name="excelFileName">Excel表名字</param>
    /// <returns></returns>
    public static string GetExcelFirstTableName(string excelFileName)
    {
    string tableName = null;
    if (File.Exists(excelFileName))
    {
    string excelStr = "Provider= Microsoft.Ace.OleDB.12.0;Data Source=" + excelFileName + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";
    using (OleDbConnection conn = new OleDbConnection(excelStr))
    {
    conn.Open();
    DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);//获取table内容
    tableName = dt.Rows[0][2].ToString().Trim();
    }
    }
    return tableName;
    }

  • 相关阅读:
    Nginx安装与运行配置总结
    不知道为什么随笔分类出不来
    springboot打war包
    python爬取网站页面时,部分标签无指定属性而报错
    python爬取某站新闻,并分析最近新闻关键词
    插了带蠕虫的U盘后,文件不见了怎么快速恢复
    CompTIA Security+ 常见知识点
    JAVA学习--集合的遍历
    JAVA学习--ArrayList使用方法:List的主要实现类
    JAVA学习--异常Exception的处理
  • 原文地址:https://www.cnblogs.com/zilinyufeng/p/4138141.html
Copyright © 2011-2022 走看看