Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

c# - 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:myFoldermyOldExcelFile.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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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_MACHINESOFTWAREMicrosoftOffice14.0Access Connectivity EngineEnginesExcel

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...