簡體   English   中英

不使用OLEDB在c#中顯示所有Excel單元格值

[英]Does not display all Excel cell values in c# using OLEDB

我在ac#列表框上顯示Excel單元格值時遇到此問題。

我有這個Employees.xls文件,其中包含四(4)列(“代碼”,“姓氏”,“名字”,“中間名”)。

具體內容如下:

Code   LastName   FirstName   MiddleName

1      Dela Cruz  Juan        Santos

2      Severino   Miguel      Reyes

現在使用Openfile對話框,我瀏覽了文件並希望在列表框上顯示列標題。

結果應該是:

Code

LastName

FirstName

MiddleName

問題是當我瀏覽文件時,未顯示列標題“代碼”。

它僅顯示:

      <--- (Blank Space)

LastName

FirstName

MiddleName

我注意到為第一個值提供了一個空格,但未顯示“代碼”文本。

這是我用來獲取單元格值的代碼:

  private void btn_Browse_Click(object sender, EventArgs e) // Browse Button

     {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        openFileDialog1.InitialDirectory = "c:\\";
        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;
        this.lbl_Path.Text = openFileDialog1.FileName;
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
         {
             try
             {
                 if ((myStream = openFileDialog1.OpenFile()) != null)
                 {
                     using (myStream)
                     {
                         this.lbl_Path.Text = openFileDialog1.FileName;
                         source = openFileDialog1.FileName.Replace(@"\", @"\\");
                         this.lbl_Path.Visible = true;
                         GetExcelSheetNames(source);
                         lst_Fields.Items.Clear();
                         string SheetName = sheet;
                         string query = "Select * From ["+SheetName+"]";
                         DataTable table = conExcel(query);
                         int i = 0;
                         lst_Fields.Items.Add(Convert.ToString(table.Rows[i][0]));
                         lst_Fields.Items.Add(Convert.ToString(table.Rows[i][1]));
                         lst_Fields.Items.Add(Convert.ToString(table.Rows[i][2]));
                         lst_Fields.Items.Add(Convert.ToString(table.Rows[i][3]));
                         lst_Fields.Items.Add(Convert.ToString(table.Rows[i][4]));
                         lst_Fields.Items.Add(Convert.ToString(table.Rows[i][5]));
                         lst_Fields.Items.Add(Convert.ToString(table.Rows[i][6]));
                         lst_Fields.Items.Add(Convert.ToString(table.Rows[i][7]));
                         lst_Fields.Items.Add(Convert.ToString(table.Rows[i][8]));
                         lst_Fields.Items.Add(Convert.ToString(table.Rows[i][9]));
                     }

                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
             } 
         }
    }

    private DataTable conExcel(string query) // Connection to Excel
    {
        OleDbConnection conn = new OleDbConnection();
        conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + source + ";Extended Properties=\"Excel 12.0;HDR=NO;IMEX=-1;\"";
        conn.Open();
        OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
        DataTable table = new DataTable();
        da.Fill(table);
        conn.Close();
        return table;
    }

    private String[] GetExcelSheetNames(string excelFile) //Getting the sheet name
    {
        OleDbConnection objConn = null;
        System.Data.DataTable dt = null;

        try
        {
            // Connection String. Change the excel file to the file you
            // will search.
            String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + source + ";Extended Properties=\"Excel 12.0;HDR=NO;IMEX=-1;\"";
            // Create connection object by using the preceding connection string.
            objConn = new OleDbConnection(connString);
            // Open connection with the database.
            objConn.Open();
            // Get the data table containg the schema guid.
            dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            if (dt == null)
            {
                return null;
            }

            String[] excelSheets = new String[dt.Rows.Count];
            int i = 0;

            // Add the sheet name to the string array.
            foreach (DataRow row in dt.Rows)
            {
                excelSheets[i] = row["TABLE_NAME"].ToString();
                i++;
            }

            // Loop through all of the sheets if you want too...
            for (int j = 0; j < excelSheets.Length; j++)
            {
                sheet = excelSheets[0];
            }

            return excelSheets;
        }
        catch (Exception ex)
        {
            return null;
        }
        finally
        {
            // Clean up.
            if (objConn != null)
            {
                objConn.Close();
                objConn.Dispose();
            }
            if (dt != null)
            {
                dt.Dispose();
            }
        }
    }

嘗試將IMEX=-1更改為IMEX=1

如果仍然無法使用,請嘗試使用google將Excel數據視為文本。

編輯:

對於XLS文件, Excel 8.0; 應該在擴展屬性中使用

來源: http//www.connectionstrings.com/ace-oledb-12-0/

將conExcel方法中的連接字符串更改為期望的標題。

conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + source + ";Extended Properties=Excel 12.0;HDR=YES;";
// OR
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + source + ";Extended Properties=Excel 12.0;HDR=YES;IMEX=1";
//conn.ConnectionString = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + source + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=-1;\"";

然后,您可以更改:

lst_Fields.Items.Add(Convert.ToString(table.Rows[i][0]));
lst_Fields.Items.Add(Convert.ToString(table.Rows[i][1]));
lst_Fields.Items.Add(Convert.ToString(table.Rows[i][2]));
lst_Fields.Items.Add(Convert.ToString(table.Rows[i][3]));
lst_Fields.Items.Add(Convert.ToString(table.Rows[i][4]));
lst_Fields.Items.Add(Convert.ToString(table.Rows[i][5]));
lst_Fields.Items.Add(Convert.ToString(table.Rows[i][6]));
lst_Fields.Items.Add(Convert.ToString(table.Rows[i][7]));
lst_Fields.Items.Add(Convert.ToString(table.Rows[i][8]));
lst_Fields.Items.Add(Convert.ToString(table.Rows[i][9]));

至:

foreach (DataColumn dc in table.Columns)
{
    lst_Fields.Items.Add(dc.ColumnName);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM