C# Script to open and read an Excel spreadsheet with multiple worksheets

Can someone provide me the C# syntax and Edit Script to open an Excel spreadsheet with multiple worksheets and then using the data to create and output a .csv file? The multiple worksheets contain different data elements that I'll need to parse out and then
store as a .csv file that will then be read to pump data into our SQL Server Database.
Thanks for your review and am hopeful for a reply.
PSULionRP

I think this code originally came from Joel, who comes here quite a bit.  I'm not a C# expert, like Joe is, but I think this is pretty close to what you want.
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;
using Microsoft.Office.Interop.Excel;
using System.IO;
namespace WindowsFormsApplication2
public partial class Form1 : Form
public Form1()
InitializeComponent();
private void button1_Click(object sender, EventArgs e)
Main();
public void Main()
string filePath = "C:\\Users\\Ryan\\Desktop\\MainExcel.xlsx";
Microsoft.Office.Interop.Excel.Application xlobj = new Microsoft.Office.Interop.Excel.Application();
Workbook w = default(Workbook);
Workbook w1 = default(Workbook);
Worksheet s = default(Worksheet);
Worksheet s1 = default(Worksheet);
Worksheet xlsht = default(Worksheet);
xlobj.Visible = true;
int intItem = 1;
DirectoryInfo dirSrc = new DirectoryInfo(@"C:\Users\Ryan\Desktop\Test_Folder\");
foreach (FileInfo ChildFile in dirSrc.GetFiles())
try
// Renaming the excel sheet
w = xlobj.Workbooks._Open(ChildFile.FullName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
w1 = xlobj.Workbooks._Open(filePath,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
//this doesn't make any sense
//w1 = xlobj.Workbooks.Open(filePath);
//if (intItem > 3)
Excel.Worksheet lastSht =
(Excel.Worksheet)w1.Worksheets[w1.Worksheets.Count];
xlsht = (Excel.Worksheet)w1.Worksheets.Add(Type.Missing,
lastSht,
Type.Missing, Type.Missing);
s = (Excel.Worksheet)w.Worksheets[1];
s1 = (Excel.Worksheet)w1.Worksheets[intItem];
s1.Name = ChildFile.Name;
// it will copy and paste sheet from one to another with formula
s.UsedRange.Copy(Type.Missing);
Excel.Range r = s1.get_Range("A1", Type.Missing);
r.PasteSpecial(Excel.XlPasteType.xlPasteValues,
Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone,
Type.Missing, Type.Missing);
s1.UsedRange.Formula = s.UsedRange.Formula;
// Renaming the excel sheet
//w.Save();
w.Close(false, Type.Missing, Type.Missing);
w1.Close(false, Type.Missing, Type.Missing);
catch (Exception ex)
//w.Save();
w1.Save();
w.Close(false, Type.Missing, Type.Missing);
w1.Close(false, Type.Missing, Type.Missing);
intItem = intItem + 1;
//Dts.TaskResult = ScriptResults.Success
Do you need help getting everything into a CSV, or can you take it from here???
Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

Similar Messages

  • Excel Upload With Multiple Worksheets

    Friends,
    I have requirement wherein I have to read data from an excel file with multiple worksheets. I have gone through some earlier postings but most of them explain about creating an excel file with multiple worksheets (which is right oppsite of what I need to do)
    I am trying to understand the concept of OLE and implement it but am finding it tricky!
    Please help me out!
    Thanks,
    Shyam

    See this site: AN EASY REFERENCE FOR OLE AUTOMATION by Serder Simsekler.
    Best!
    Jim

  • Excel download with multiple worksheets using ABAP webdynpro

    Content of Internal table should to downloaded  to an excel sheet with multiple worksheet.

    Excel doesn't support multiple worksheets with the text tab delimited or any of the other plain text formats.  So if you need multiple worksheets those approaches are out.  Multiple worksheets would only work with the Excel native format or the XML based format.  From ABAP the best approach would be to create the XML Excel format.  Search the forms and wiki has there has been tons of discussion in the mast on the XML Excel format.

  • Automation Open and Automation Close (Excel)

    Hi
    I am using ActiveX to write and read from Excel.
    I am writing a program which a case statement is involved. When the boolean is true, the program in the case statment (View Result.VI) will open Excel and display the last save filename file. I run this program individually and not part of the main.vi program.
    It displays the filename but once I close the file, the Excel also closed which I don't want it to do that.
    I run my Main.vi (together with the View Saved Result.vi) and when I want to view the result, the program open Excel, but then, the screen hang and does not load the Excel properly. But when I run the View Saved Result.Vi, it does load properly.
    I was wondering should I use Automation Close f
    or every Excel workbook, worksheet or Invoke nodes which I have used in my program.
    Please look at my JPEG file for understanding.
    Thanks,
    jun
    Attachments:
    Capture_3.jpg ‏53 KB

    I would not call Automation Close for each one. Once you call Automation Close, Excel will exit. That's just how ActiveX is built to work. As long as you want to leave the application open, you shouldn't close the ActiveX Automation controller.
    I would actually suggest gettings the LabVIEW Report Generation Toolset for Microsoft Office. I have found it to be extremely helpful and it's actually quite easy to do what you're wanting to do with this Toolset.
    J.R. Allen

  • Problems with Firefox 7.0.1 , gmail and MacOSX 10.6.8---gmail not working-can't select, open and read mail!!! help---anyone?

    I can select and delete, but not open and read...
    things are working mighty slow since installing 7.0.1 Firefox upgrade....and losing access to reading gmail is just the last straw.
    Also having issues with non-responsive script messages in same gmail window, huge time lags, some flash plug in error messages (yes three times I have downloaded and reinstalled the latest flash player)....hating 7.0.1 right now mightily....

    I came across this and it worked for me.
    GMail entire message content missing (blank) after header title
    In Firefox, if you have "Adblock Plus" extension.
    1. "Ctrl+Shift+F" Preferences (or right click on ADP symbol, and choose preferences)
    2. 'Filters' menu > "Update all subscriptions"
    reference: https://support.mozilla.com/questions/896267

  • App-V PowerShell: Script to Query XenApp Servers for App-V Publishing Errors and Output an Excel Document with the Results

    Please Vote if you find this to be helpful!
    App-V PowerShell:  Script to Query XenApp Servers for App-V Publishing Errors and Output an Excel Document with the Results
    Just posted this to the wiki:
    http://social.technet.microsoft.com/wiki/contents/articles/25323.app-v-powershell-script-to-query-xenapp-servers-for-app-v-publishing-errors-and-output-an-excel-document-with-the-results.aspx

    Hi petro_jemes,
    Just a little claritification, you need to add the value to the variable "[string]$ou", and also change the language in the variable "$emailbody" in the function "Get-ADUserPasswordExpirationDate".
    I hope this helps.

  • Open and read from text file into a text box for Windows Store

    I wish to open and read from a text file into a text box in C# for the Windows Store using VS Express 2012 for Windows 8.
    Can anyone point me to sample code and tutorials specifically for Windows Store using C#.
    Is it possible to add a Text file in Windows Store. This option only seems to be available in Visual C#.
    Thanks
    Wendel

    This is a simple sample for Read/Load Text file from IsolateStorage and Read file from InstalledLocation (this folder only can be read)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Storage;
    using System.IO;
    namespace TextFileDemo
    public class TextFileHelper
    async public static Task<bool> SaveTextFileToIsolateStorageAsync(string filename, string data)
    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(data);
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    try
    using (var s = await file.OpenStreamForWriteAsync())
    s.Write(fileBytes, 0, fileBytes.Length);
    return true;
    catch
    return false;
    async public static Task<string> LoadTextFileFormIsolateStorageAsync(string filename)
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    string returnvalue = string.Empty;
    try
    var file = await local.OpenStreamForReadAsync(filename);
    using (StreamReader streamReader = new StreamReader(file))
    returnvalue = streamReader.ReadToEnd();
    catch (Exception ex)
    // do somthing when exception
    return returnvalue;
    async public static Task<string> LoadTextFileFormInstalledLocationAsync(string filename)
    StorageFolder local = Windows.ApplicationModel.Package.Current.InstalledLocation;
    string returnvalue = string.Empty;
    try
    var file = await local.OpenStreamForReadAsync(filename);
    using (StreamReader streamReader = new StreamReader(file))
    returnvalue = streamReader.ReadToEnd();
    catch (Exception ex)
    // do somthing when exception
    return returnvalue;
    show how to use it as below
    async private void Button_Click(object sender, RoutedEventArgs e)
    string txt =await TextFileHelper.LoadTextFileFormInstalledLocationAsync("TextFile1.txt");
    Debug.WriteLine(txt);
    在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。

  • How to open and read many files from a directory and store contents in 2D array?

    I want to make a VI that opens and reads the data from various files contained in a directory (200 files each with 2 columns) and store these in a single 2D array. For file number 1 I want to store the data from both columns in the 2D array, but for files 2 to 200 I only want to store the second column of each file. Can someone please help?

    Hi Nadav,
    Thanks for your help. I have followed your instructions but i cannot get it to work. I used the LIST DIRECTORY to list the files in the directory - that works. However, how do I read each of the 200 files using READ FROM SPREADSHEET FILE without me having to manually select each of the 200 files? So, if I use LIST DIRECTORY to list all 200 files in an array, how do I get each of these to open and store the data in a 2D array? Here is what I have done (File called read_files.VI) Could you please help me? Thank you very much in advance.
    Attachments:
    read_files.vi ‏18 KB

  • How to open and read an external file in Dashboard widget?

    I am new to Dashboard widgets and also Javascript. I have written a widget that needs to open and read a file on the local file system. I have searched a lot and have not found any documentation or reference on the internet as to how to do this.
    I know it can be done since there is a checkbox in the widget attributes that says "Allow External File Access".
    can anyone help me out here?
    Thanks

    You need to define the AllowFileAccessOutsideOfWidget key to Yes.
    You also need to define the AllowFullAccess key.
    You may also need to define the AllowSystem key (to Yes of course).
    Mihalis.
    PS. If you cannot find any other documentation please check http://widgetbook.blogspot.com.

  • How to open and read pdf and micrsoft word (.doc) files or documents

    My problem is how to use my BB 9800 software version 6.0.0.546 to read/view pdf files and microsoft office documents. I have also bought documents to go from online and have installed it on my phone, but whenever i try to open it I receive a message that it is incompactible. Any help will be greatly appreciated.

    Hi, Sammy.
    Why not install a 3rd party PDF reader and Word Doc reader to help open and read pdf and micrsoft word (.doc) files or documents? You can google it and select one whose way of processing is simple and fast to help you with the related converting work.  It will be better if it is totally manual and can be customized by users according to our own favors. Remember to check its free trial package first if possible. I hope you success. Good luck.
    Best regards,
    Arron

  • How to open and read binary files?

    How do I open and read Binary files?

    Did you  look on The Unarchiver's web site where it has a link to older versions? http://theunarchiver.googlecode.com/files/TheUnarchiver3.2_legacy.zip
    The best thing to do is ask your friends what programs they used to produce these files, or at least what format files they are producing.  Otherwise it's like being shown a car and given a bundle of 200 keys with no idea to which one to use, or even if any of them work with that car.
    Using The Unarchiver will likely not do anything because it too will not know what format files are involved, and they may not even been in an archived format.  If they sent you a Word file without telling you (a favorite of Windows users to do  -- it drives me crazy when they could have just sent them in plain text), The Unarchiver won't open them.  If it's a picture file then using Hexedit will just show you a bunch of unintelligible stuff as shown in an earlier post, though you may see a line of text providing a hint.
    As I said earlier, often .bin may be an executable program which needs another program to actually interpret it.  That's what Java is trying to do.  Still, it may think it can execute the file, but it is highly unlikely somebody would send you an executable program (and if they did I would not trust it).  For all you know it may be a Windows virus.

  • Hi... I would like to purchase a Tablet Sony Xperia Z 2 10.1 (the last one of the Z series) and I was told that Adobe does not support Sony anymore.... I need to be able to open and read Adobe PDF files and I would like to know if this tablet can still us

    Hi... I would like to purchase a Tablet Sony Xperia Z 2 10.1 (the last one of the Z series) and I was told that Adobe does not support Sony anymore.... I need to be able to open and read Adobe PDF files and I would like to know if this tablet can still use Flash Player...
    Is there anyo who can help me with this? I asked in the shop and I was told "yes of course" , but when I contacted Sony directly I was advised to check with Adobe as apparently in the recent months Adobe and Sony haven't been getting along anymore...

    You may be mixing up two entirely different Adobe products.
    1. Adobe Flash Player. Needed to view web pages designed with Flash. Not needed to view PDF files. Not available for Android (not just Sony).
    2. Adobe Reader. Reads PDF files. However, the Android can also read most PDF files without needing Adobe Reader.

  • Hi,how can i change the default settings on my adobe readerX1 such that it will display all my pdf files according to their individual cover pages (as cover picture thumbnails)before i click them to open and read........i really enjoyed this feature as a

    hi,how can i change the default settings on my adobe readerX1 such that it will display all my pdf files according to their individual cover pages (as cover picture thumbnails)before i click them to open and read........i really enjoyed this feature as a default settings upon installation in previous editions of adobe reader .i use a windows 8 pc now.thank

    For sideloaded content the nook pulls the metadata from ePub file itself.  I would suggest looking at a program like Sigil or Calibre that will let you edit the metadata in the book to make it appear like you want.
    For the PDF vs ePub - No, that's the way PDFs work (think of them as graphics, not text), wheres ePubs are Web Pages - so  no you can't them to behave exactly alike without converting the files.

  • I bought a pdf book last year and had no problem reading it for a few months then all of a sudden I could no longer open it and to this day. Any other pdf download off internet I can still open and read, except for that particular book. Operating system i

    I bought a pdf book last year and had no problem reading it for a few months then all of a sudden I could no longer open it and to this day. Any other pdf download off internet I can still open and read, except for that particular book. Operating system is Windows 7 Home Premium, Adobe Reader XI 11.0.07.  When trying to open file I get msg "You did'nt login or your session has expired. Please log in to read this document for the first time". (Like I said I have read it before). So I log in but that prompts me to give the name of the file I want to export or convert to Word or something else, which is not what I want to do of course. I have not purchased any service from Adobe or Acrobat as I only need to read. Thanks for your help..

    Thank you for your reply. Operating system is Windows 7 Home Premium, Adobe Reader XI 11.0.07.  When trying to open file I get msg "You did'nt login or your session has expired. Please log in to read this document for the first time". (Like I said I have read it before). So I log in but that prompts me to give the name of the file I want to export or convert to Word or something else, which is not what I want to do of course. I have not purchased any service from Adobe or Acrobat as I only need to read. Thanks for your help.

  • FYI TDMS open and read on empty file gives no error's out

    I found that if you 'open' an empty (0 byte) file using TDMS open, you will not get any error messages when you open it, nor when you call functions such as "Get properties" or "List content", also no error when you close the TDMS file.
    If the file is non-empty, but not a valid TDMS file, TDMS open returns an error.
    I would have expected that I would get an error or a warning at least when trying to read a non-existant property or group, if not by the open function itself?!
    The 2013 snippet below creates a 1-byte or empty file in the local user temporary folder, closes the file, then attempts to open and read it as a TDMS file.  The temporary file is deleted afterwards.
    If the file is empty, NO errors or warnings occur at any point.  If the file is not empty, it fails on the TDMS open. (Note the sequence structure is because the path out of the tdms close is invalid if the tdms open failed.
    This could conceivably cause an issue if your program does not do additional fault checking to catch existing but empty files.  (Which of course shouldn't ever happen, but in some situations it could happen.)
    QFang
    CLD LabVIEW 7.1 to 2013

    Hooovahh
    I asked to list the channels in a named group.  If that named group did not exist, I would think that should at least be a warning,  but I could see how it should not be an error, it was just unexpected to me that reading a non existant group (in an empty file) did not indicate any issues at all.   To me, 'error out' should give a warning or an error if something unexpected happened, but I may just have stricter opinion on something that by nature is very philosophical and open for debate. (And there are always tradeoffs, overt checks and bounds in a function obviously leads to overhead, and TDMS is optimized for performance, so that may be one reason it is the way it is.)
    (This situation came up for me because when a file is first created, we datetime tag it and write a bunch of other meta-data to the file, then later (and over time) we add the spectrum goup + data.  [Edit] actually, in the old code, if the file existed, it was assumed to have been setup correctly. so if the group exists, the old code assumed all the meta data has already been written [end edit].. One of the many fixes possible, I'll rely on the 'found' boolean output of the parameter read instead of relying on the error/warning. If the datetime tag is found, the code will asume the file exists and has been filled with the meta data I expect.)
    Thoult ::  I wasn't sure, but in either case, my intent was to provide extra information, not 'knock you' for participating in the discussion, I hope thats not how I came accross.  English is a second language to me, so I sometimes come across 'wrong' from what I mean.
    QFang
    CLD LabVIEW 7.1 to 2013

Maybe you are looking for

  • IOS 4 backup restoring onto iOS 7.0.3

    Is a backup from iOS 4 able to restore onto a device running iOS 7.0.3? Assume best senario where no other software or hardware issues apply.

  • How to call a BAPI when there are structure tables as Input.

    Environment: Data Services 3.1  SAP ECC 6. I can run simple BAPI's where I just populate the Input Parameters. My question is around more complex BAPI's. I created a data flow that looks like: Row Generation > Query > Unnest Query > Template table. I

  • Strange battery issue

    My wife's 4S has been running down about 50% overnight in standby so I decided to investigate it. The basic problem is that it is showing a usage figure of almost the same as the standby figure while in standby indicating that something is running. A

  • [SOLVED] tomcat + deploy openlaszlo = java error

    Hi all, I installed tomcat using shaman, everything went well. But when putting OpenLaszlo.war in the Tomcat Manager and going to deploy it. I always get this error. Here's the screenshot type Exception report description The server encountered an in

  • Turning printer to online with windows 8

    I have spent the last few hours reading and trying everything I could to get my printer in the online position. Then I came across a small blurb that suggested shutting everything off. Everything! I had turned of my computer several times and reloade