Handling of the error "External table is not in the expected format" when connecting to excel

Source: Internet
Author: User

For files. the Excel File Created by create (filename), although in the format of Excel files, is not a standard Excel file. When using ado.net to connect to this file, the error message "The External table is not in the expected format" is displayed. This type of file is opened in the same format as the TXT file.

To solve the problem of an Excel file that prompts "The External table is not in the expected format", read the datatable file in the file reading mode and then process it.

 

// Read the file and the memory table exists.

Private datatable readfile (string filename, int columnnum)

{

Datatable dataread = createdatatable (columnnum );

If (file. exists (filename ))

{

String strread; // stores the Read File data.

Encoding encoding = encoding. getencoding ("gb18030 ");

Try

{

Filestream FS = new filestream (filename, filemode. Open, fileaccess. Read, fileshare. readwrite );

Streamreader sr = new streamreader (FS, encoding );

Strread = Sr. readtoend ();

Sr. Close ();

FS. Close ();

// Import the memory datatable

String [] readarray = strread. Split (New char [] {'/N'}, stringsplitoptions. removeemptyentries );

Foreach (string row in readarray)

{

String [] column = row. replace ("",""). replace ("/R ",""). split (New char [] {'/t'}, stringsplitoptions. removeemptyentries );

Datarow DR = dataread. newrow ();

For (INT I = 0; I <column. length; I ++)

{

Dr [I] = column [I];

}

Dataread. Rows. Add (DR );

}

}

Catch (exception ex)

{

Console. Write (ex. tostring ());

}

}

Else

{

MessageBox. Show ("file missing ");

}

Return dataread;

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.