C# importing a spreadsheet

acole1

Golden Member
Sep 28, 2005
1,543
0
0
I have the code to import a spreadsheet into a datagrid, but it only works if I know the name of the spreadsheet I want to import.

I am needing to select the second spreadsheet of a workbook, no matter what its name is. Is there a way to do this?
 

KIAman

Diamond Member
Mar 7, 2001
3,342
23
81
Is this web or app? If app use OpenFileDialog, if web use html input type file and runat server so you can reference it in codebehind.
 

acole1

Golden Member
Sep 28, 2005
1,543
0
0
It is a Windows Forms application.

I am able to find the sheet names using code from here (http://www.codeproject.com/KB/aspnet/getsheetnames.aspx). I am still working to get it fully functioning in the program how I need it.



Each time a sheet name is found I do a call to my old import method. That import method looks at the index for the sheet quantity and assigns it to a dataGridView based on that index.

E.g. if (i = 0) { dataGridView1.DataSource = dt } else if (i = 1) { dataGridView2.DataSource = dt } ... etc.

The problem I have now, is that on the 2nd call to the import method the code just dies after it runs da.Fill(dt). It never even checks the sheet index or assigns the data table to the datagridview. I even check to see if it gets to the end of the import method, but the flag is never triggered.
 
Last edited:

KIAman

Diamond Member
Mar 7, 2001
3,342
23
81
I didn't read your OP closely enough. If you are calling your import method from inside the sheetname code, you might be running into an open connection issue because the sheetname code does not call the close method until the finally block.
 

acole1

Golden Member
Sep 28, 2005
1,543
0
0
I shifted the code around so the Import method calls the sheetname method. Now on the 2nd da.Fill(dt) call I get the error "Too many fields defined." This may have been the problem all along. I will work on a fix for the error tomorrow.
 

joutlaw

Golden Member
Feb 18, 2008
1,108
2
81
You should look at DatagridView Extensions. I know they have export functionality built in... datagrid to excel, so I imagine they have import too.

It saved me a lot of time and frustration. Also the Excel interop has logic to call different sheets... I believe they are 0 based.