简体   繁体   中英

Read excel columns as text

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 connection string used. Only ACE driver is installed and we can't use any other drivers in production server.

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myOldExcelFile.xls;
                             Extended Properties="Excel 12.0;HDR=YES;IMEX=1";

Setting IMEX=1 doesn't work. It returns null for some values.

I could see a lot of articles but am couldn't see a right answer.

Any help would be appreciated.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM