473,320 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Grab Spreadsheet names then read each in Foreach

dbrewerton
115 100+
Ok, I am trying to figure out the best way to accomplish this in code. I have a spreadsheet with numerous tabs and what I want to do is in C# read the name of each sheet and then its corresponding rows of data. Currently, this is what I have:

Expand|Select|Wrap|Line Numbers
  1.             if (!DirectoryIsEmpty(DropZone.ToString()))
  2.             {
  3.  
  4.                 DirectoryInfo di = new DirectoryInfo(DropZone);
  5.                 FileInfo[] fi = di.GetFiles();
  6.                 // step through each found file
  7.                 foreach (FileInfo fiTemp in fi)
  8.                 {
  9.                     //    Connection String to Excel Workbook
  10.                     string excelConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + DropZone + "\\" + fiTemp + "'; Extended Properties=\"Excel 8.0; HDR=YES; IMEX=1;\"";
  11.                     string SheetName = string.Empty;
  12.                     //    Create Connection to Excel Workbook
  13.                     using (OleDbConnection connection = new OleDbConnection(excelConnStr))
  14.                     {
  15.                         try
  16.                         {
  17.                             string curaddy2 = string.Empty;
  18.                             string priaddy2 = string.Empty;
  19.                             connection.Open();
  20.                             DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
  21.                             if (dt != null)
  22.                             {
  23.                                 string[] excelSheets = new String[dt.Rows.Count];
  24.                                 int i = 0;
  25.                                 foreach (DataRow row in dt.Rows)
  26.                                 {
  27.                                     excelSheets[i] = row["TABLE_NAME"].ToString();                                    
  28.                                     #region ExcelReading
  29.                                     SheetName = excelSheets[i].ToString();
  30.                                     OleDbCommand command = new OleDbCommand("SELECT [Name], [Address], [City], [State], [Zip] FROM '" + SheetName.ToString() + "'", connection);
  31.                                     using (DbDataReader dr = command.ExecuteReader())
  32.                                     {
  33.                                         // SQL Server Connection String
  34.  
  35.                                         string sqlConnectionString = DBUtils.DBString;
  36.                                         // Bulk Copy to SQL Server
  37.                                         using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
  38.                                         {
  39.                         // Columns get copied from sheet and into bulk copy statement
  40.                                             logger.MyLogFile("" + DateTime.Now.ToString() + " Bulk Copy: ", "ID Number " + dr.GetValue(0).ToString() + "");
  41.                                             // now that matrix is created, do the insert
  42.                                             bulkCopy.DestinationTableName = "Table";
  43.                                             bulkCopy.WriteToServer(dr);
  44.                                             logger.MyLogFile("" + DateTime.Now.ToString() + " Bulk Copy: ", "All values inserted as burst");
  45.                                         }
  46.                                     }
  47.                                     #endregion
  48.                                     i++;
  49.                                 }
  50.                             }
  51.                             dt.Dispose();
  52.                         }
  53.                         catch (Exception ex)
  54.                         {
  55.                             logger.MyLogFile("" + DateTime.Now.ToString() + " Importer \n", "Import failed, error code: " + ex.ToString() + "");
  56.                         }                        
  57.                         finally
  58.                         {                            
  59.                             connection.Close();
  60.                         }
  61.                     }
  62.                 }
  63.  
Oct 23 '14 #1
0 1128

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Matt | last post by:
While i am looping the records how i do for each field name while(objRead.Read()) foreach( { match(x) Console.WriteLine(objRead.); }
6
by: syvman | last post by:
Hi everyone... I am pulling my hair out trying to do this, and was wondering if someone could give me some assistance... I have an Excel spreadsheet containing several worksheets. I'd like to be...
6
by: Syvman | last post by:
Here's what I've got: I'm trying to grab some data out of an Excel spreadsheet and bring it into Access. I'm able to do it, but only if the Excel spreadsheet is not opened by any other users. I...
0
by: JLuv | last post by:
What i want to do is take the checked data from a datagrid, send it to a table, then show that table on an Excel Spreadsheet. Here is a little bit of my code... //adminProgress.aspx...
0
by: mix01 | last post by:
Hi, I am trying to get some VBA code working, but am preplex as to why it does not work. I would really appreciate any level of help. Many thanks, Mix01 Version of the program
2
by: KC-Mass | last post by:
Is it possible to read the spreadsheet names in an Excel workbook with VBA and no Excel?
2
by: testingPerl | last post by:
Hey everyone. I'm using Spreadsheet::Read to grab data from an excel .xls file and I can't figure out how to loop through the hash and display the data. Using print works but I would like to print...
14
by: lashaw | last post by:
This program display a names. If the name you type match the one asked to type, the program tells you the phone number of the name. The problem is it only list the last name in the file. How to get...
5
by: tamcgly33 | last post by:
I need to grab field names from a table. The table is all yes/no fields with the exception of the key field. I need all the field names that have a value of "yes".
24
by: PrezWeezy | last post by:
I am attempting to create a loop to read through each XML attribute in a node and put it into a datatable. I have created my datatable with columns that are the same name as the attributes in my...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.