Read excel columns as text

后端 未结 1 1443
春和景丽
春和景丽 2020-12-18 17:39

I want to read all columns as text values only from an excel file in a web application irrespective of the type of the data(date, number etc).

Please see the connect

1条回答
  •  时光说笑
    2020-12-18 17:40

    I think this is what you are after ACE work around

    Unfortunately, you can't set ImportMixedTypes or TypeGuessRows from the connection string since those settings are defined in the registry. For the ACE OleDb driver, they're stored at

    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Access Connectivity Engine\Engines\Excel

    in the registry. So, you can simplify your connection string to get rid of some of those extended properties.

    Once you set TypeGuessRows to 0 and ImportMixedTypes to Text in the registry, you should get the behavior you are expecting.


    Or you can use Microsoft.Office.Interop.Excel to read the file. Sample code:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    using Excel = Microsoft.Office.Interop.Excel;
    
    namespace ExcelTut
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                Excel.Application xlApp = new Excel.Application();
                Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:/C.xlsx");
                Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
                Excel.Range xlRange = xlWorksheet.UsedRange;
    
                int rowCount = xlRange.Rows.Count;
                int colCount = xlRange.Columns.Count;
    
                for (int i = 1; i <= rowCount; i++)
                {
                    for (int j = 1; j <= colCount; j++)
                    {
                        MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());
                    }
                }
    
            }
    
        }
    }
    

    code taken from read excel file via interop

    0 讨论(0)
提交回复
热议问题