How can I load an Excel File to a pipe-delimited .csv File

In SSIS I am attempting to process a .xls File and I have a C# script that is reading the .xls File. My issue is this...I have some fields that have an embedded comma in them. Those fields are designated by a double quote though ". I have included my
C# Script. I'm just not sure if I have to indicate to it that there is a field delimeter. The " double-quote is only utilized when there is indeed an embedded comma...like "Company Name, Inc"...or "Main St., Apt. 101"
How can I read this .xls worksheet and account for the double-quotes and the embedded comma and produce a pipe-delimeted file?
public void Main()
// TODO: Add your code here
// Create NEW .CSV Files for each .XLS File in the Directory as .CSV Stubs to store the records that will be re-formatted
// in this Script.
try
string StringExcelPath = (Dts.Variables["User::FilePath"].Value.ToString());
string StringExcelFileName = (Dts.Variables["User::FileName"].Value.ToString());
string StringFileNameExtension = Path.GetExtension(StringExcelFileName);
if (StringFileNameExtension != ".xls")
return;
string StringCSVFileName = (Dts.Variables["User::FileName"].Value.ToString());
StringCSVFileName = Path.GetFileNameWithoutExtension(StringCSVFileName);
StringCSVFileName = (Dts.Variables["User::FilePath"].Value.ToString()) + StringCSVFileName + ".csv";
string StringExcelWorksheetName = (Dts.Variables["User::ExcelWorksheetName"].Value.ToString());
string StringColumnDelimeter = "|";
int IntHeaderRowsToSkip = 0;
//FileStream stream = File.Open(StringFullyQualifiedPathFileName, FileMode.Open, FileAccess.Read);
//// Reading from a binary Excel file ('97-2003 format; *.xls)
//IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//// Reading from a OpenXml Excel file (2007 format; *.xlsx)
//IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//// DataSet - The result of each spreadsheet will be created in the result.Tables
//DataSet result = excelReader.AsDataSet();
//// Free resources (IExcelDataReader is IDisposable)
//excelReader.Close();
if (ConvertExcelToCSV(StringExcelFileName, StringCSVFileName, StringExcelWorksheetName, StringColumnDelimeter, IntHeaderRowsToSkip) == true)
Dts.TaskResult = (int)ScriptResults.Success;
else
Dts.TaskResult = (int)ScriptResults.Failure;
catch (Exception)
Dts.TaskResult = (int)ScriptResults.Failure;
public static bool ConvertExcelToCSV(string sourceExcelPathAndName, string targetCSVPathAndName, string excelSheetName, string columnDelimeter, int headerRowsToSkip)
try
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook ExcelWorkBook = ExcelApp.Workbooks.Open(
sourceExcelPathAndName, // Filename
0, // UpdateLinks ===> http://msdn.microsoft.com/en-us/library/office/ff194819(v=office.15).aspx
true, // ReadOnly
5, // Format ===> http://msdn.microsoft.com/en-us/library/office/ff194819(v=office.15).aspx
"", // Password
"", // WriteResPassword
true, // IgnoreReadOnlyRecommended
Excel.XlPlatform.xlWindows, // Origin
"", // Delimeter
true, // Editable
false, // Notify
0, // Converter
false, // AddToMru
false, // Local
false // CorruptLoad
// Gets the List of ALL Excel Worksheets within the Excel Spreadsheet
Excel.Sheets ExcelWorkSheets = ExcelWorkBook.Worksheets;
// Retrieves the Data from the EXACT Excel Worksheet that you want to process from
Excel.Worksheet ExcelWorksheetToProcess = ExcelWorkSheets.get_Item(excelSheetName);
// Gets the Range of Data from the EXACT Excel Worksheet that you want to process from
Excel.Range ExcelWorksheetRange = ExcelWorksheetToProcess.UsedRange;
// Sets the Cursor/Pointer at the Top Row of the Excel Worksheet
Excel.Range ExcelRangeCurrentRow;
// Deletes the Header Row and however many rows as specified in headerRowsToSkip
for (int ExcelRowCount = 0; ExcelRowCount < headerRowsToSkip; ExcelRowCount++)
ExcelRangeCurrentRow = ExcelWorksheetRange.get_Range("A1", Type.Missing).EntireRow;
ExcelRangeCurrentRow.Delete(XlDeleteShiftDirection.xlShiftUp);
// Replace ENTER, "\n", with a Space " "
//ExcelWorksheetRange.Replace("\n", " ", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Replace comma "," with the indicated Column Delimeter variable, columnDelimeter
ExcelWorksheetRange.Replace(",", columnDelimeter, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Saves Data File as .csv Format
ExcelWorkBook.SaveAs(
targetCSVPathAndName, // Filename (See http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.saveas.aspx)
XlFileFormat.xlCSVMSDOS, // FileFormat
Type.Missing, // Password
Type.Missing, // WriteResPassword
Type.Missing, // ReadOnlyRecommended
Type.Missing, // CreateBackup
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, // AccessMode
Type.Missing, // ConflictResolution
Type.Missing, // AddToMru
Type.Missing, // TextCodepage
Type.Missing, // TextVisualLayout
false // Local
ExcelWorkBook.Close(false, Type.Missing, Type.Missing);
ExcelApp.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ExcelWorkSheets);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ExcelWorkBook);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ExcelApp);
return true;
catch (Exception exc)
Console.WriteLine(exc.ToString());
Console.ReadLine();
return true;
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
/// This code was generated automatically.
/// </summary>
enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
#endregion

I would prefer doing this using a standard data flow task component in SSIS. I will choose an Excel source and a flat file destination for this.
See how you can handle the inconsistent/embedded delimiters within files inside SSIS data flow
http://visakhm.blogspot.in/2014/06/ssis-tips-handling-embedded-text.html
http://visakhm.blogspot.in/2014/07/ssis-tips-handling-inconsistent-text.html
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Similar Messages

  • What is the best, most efficient way to read a .xls File and create a pipe-delimited .csv File?

    What is the best and most efficient way to read a .xls File and create a pipe-delimited .csv File?
    Thanks in advance for your review and am hopeful for a reply.
    ITBobbyP85

    You should have no trouble doing this in SSIS. Simply add a data flow with connection managers to an existing .xls file (excel connection manager) and a new .csv file (flat file). Add a source to the xls and destination to the csv, and set the destination
    csv parameter "delay validation" to true. Use an expression to define the name of the new .csv file.
    In the flat file connection manager, set the column delimiter to the pipe character.

  • How can I load a data in multiple period with a rule files?

    Hi!
    I need to create a rule file the permit me to load a record with multiple period.
    How can I do it?
    Thanks in advance.
    Bye

    As Glenn said, these two types are the typical input files.
    two ways that I can easily think of, but there are more.
    1. Have a row memberwith the period so for sample basic, the row would look lik
    cola,ny,actual,sales,Jan,100
    First case in the rule file you have to map all the member fileds with the dimension name and the data column with the data field.
    2. Have the data for each month as as the column members
    Here is the header followed by a data sample(again for sample basic)
    Product,Market,Scenario,Measure,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
    1oo-10,NY,Actual,Sales,100,100,100,100,100,100,100,010,122,111,222,333
    Second case in the rule file you have to map all the member fileds with the corresponding dimension name and the multiple data columns with the corresponding member names for that dimension.

  • How can I load a .pst file to an instrument in logic express 9?

    I have some instruments plug-in settings from my old computer that I used with logic, and I want to load them into logic so I can use them on the computer I moved them to. On any instrument I try (ES1, ES2, EXS24 and the rest) it won't allow me to load the files (.pst files) and I know I should be able to. Am I just going about it wrong or using the wrong instrument? How can I load these files so that I can use the instruments again?

    Pages is not in a format compatible for what you want to do.
    After you save a a Pages document, go to File > Export > and choose either Word or Pdf format. You can also choose RTF or PlainText too. Then you can email to yourself or others.
    Good Luck.
    Adam

  • How can I create an Excel file?

    Hi,
    How can I create an Excel file using Forms 6i.
    What I'm doing is to create a file using TEXT_IO package an name it .XLS. If a read it double-clicking over the file, it opens Ok but If I open directly from Excel it opens the Convert dialog.
    I need to create an excel file as it was made from within Excel.
    Thank in advance,
    Benjamin

    When you are talking about subfiles, are you talking like Package contents of an application?
    Terminal application in Applications -> Utilities can give a command line grasp of all your files using the du command.
    Type
    man du
    when entering the terminal, followed by the enter key.
    Note, by default the terminal opens at the Home folder.   To navigate outside the Home folder enter "/Volumes/name of mounted drive/folder/subfolder" as your path.  If there are spaces in the name, putting quotes around the whole path can help.    If you end your du command with a > name.txt a text file with the name name.txt will be plugged into your Home directory.  That you can open with Excel and parse by /es thus giving you everything in Excel.

  • How can one  read a Excel File and Upload into Table using Pl/SQL Code.

    How can one read a Excel File and Upload into Table using Pl/SQL Code.
    1. Excel File is on My PC.
    2. And I want to write a Stored Procedure or Package to do that.
    3. DataBase is on Other Server. Client-Server Environment.
    4. I am Using Toad or PlSql developer tool.

    If you would like to create a package/procedure in order to solve this problem consider using the UTL_FILE in built package, here are a few steps to get you going:
    1. Get your DBA to create directory object in oracle using the following command:
    create directory TEST_DIR as ‘directory_path’;
    Note: This directory is on the server.
    2. Grant read,write on directory directory_object_name to username;
    You can find out the directory_object_name value from dba_directories view if you are using the system user account.
    3. Logon as the user as mentioned above.
    Sample code read plain text file code, you can modify this code to suit your need (i.e. read a csv file)
    function getData(p_filename in varchar2,
    p_filepath in varchar2
    ) RETURN VARCHAR2 is
    input_file utl_file.file_type;
    --declare a buffer to read text data
    input_buffer varchar2(4000);
    begin
    --using the UTL_FILE in built package
    input_file := utl_file.fopen(p_filepath, p_filename, 'R');
    utl_file.get_line(input_file, input_buffer);
    --debug
    --dbms_output.put_line(input_buffer);
    utl_file.fclose(input_file);
    --return data
    return input_buffer;
    end;
    Hope this helps.

  • How can i load Client side XML file to Table

    Hi,
    How can i load the all the XML files (near 10,000 files) available in client machine to the XML table .
    I did try with directrory list in the Webutility demo form, but when the number of file is near to 1,500 its giving error.
    Please suggest the best method to implement my requirements.
    1. XML fies are in a folder in end users machine(Windows OS)
    2. I need to load all the XML files to table (Oracle Database is in Unix)
    I am using forms 10g
    Thanks in advance.
    Rizly

    Hi,
    What is the error you are getting when you reach 1,500 records? Can you post it? You mentioned you are using the webutil to load them. How you are loading? From the client machine you are loading to the database directly? Can you post the code you are using for that?
    -Arun

  • How can i read local excel file into internal table in webdynpro for abap a

    Could someone tell me how How can i read local excel file into an internal table in webdynpro for abap application.
    thank u for your reply

    Deep,
    File manuplations...............................
    1. At the presentation level:
    ->GUI_UPLOAD
    ->GUI_DOWNLOAD
    ->CL_GUI_FRONTEND
    2. At the application server level:
    ->OPEN DATASET : open a file in the application server for reading or writing.
    ->READ DATASET : used to read from a file on the application server that has been opened for reading
    -> TRANSFER DATASET : writing data to a file.
    -> CLOSE DATASET : closes the file
    -> DELETE DATASET : delete file
    If file is on the local PC,use the function module GUI_UPLOAD to upload it into an internal table by passing the given parameters......
    call function 'GUI_UPLOAD'
    exporting
    filename = p_file
    filetype = 'ASC'
    has_field_separator = '#'
    tables
    data_tab = t_data
    p_file : excel file path.
    t_data : internal table
    <b>reward points if useful.</b>
    regards,
    Vinod Samuel.

  • HT2470 HOW CAN I IMPORT WORD , EXCEL, POWER POINT FILES TO MICROSOFT 2011 PRELOADED IN MY I Mac ?

    HOW CAN I IMPORT WORD , EXCEL, POWER POINT FILES TO MICROSOFT 2011 PRELOADED IN MY I Mac ?

    First, don't post in all caps. It's considered shouting and very rude. As for your issue, http://answers.microsoft.com/en-us/mac

  • How can I see and excel file in my iphone 4s  THANKS

    how can I see and excel file in my iphone 4s  THANKS

    either export it as a pdf if you dont need to work in it or if you do use an app called numbers from apple it supports excel as far as i know

  • How can I access my Excel and MS word docs now that I down loaded Lion?

    How can I access my Excel and MS word docs now that I down loaded Lion?

    Isn't it the kind of question which would have been better asked before switching to Lion ?
    Of course it would be more logical to ask in a M…oSoft dedicated forum.
    In case you forgot it, here you are in a forum dedicated to an Apple product named Numbers
    Yvan KOENIG (VALLAURIS, France) samedi 23 juillet 2011 12:43:13
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8
    Please : Search for questions similar to your own before submitting them to the community
    To be the AW6 successor, iWork MUST integrate a TRUE DB, not a list organizer !

  • How can I read the EXCEL file while Program is running in background.

    Hi all Expert,
    How can I read the EXCEL file while Program is running in background.
    Thanks

    you need to place ur excel file on application server and follow this thread: Reading an Excel file from the application server?
    loots of information if you can search forum.. thanks

  • How can i import an excel file into formscentral?

    how can i import an excel file into formscentral?

    Thanks for asking.  This is not something we currently support but you can add or vote on feature ideas:
    http://forums.adobe.com/community/formscentral?view=idea
    If you need to add a new idea click "Create an idea" under "Actions" in the top right.
    Perry

  • How can I read a Excel file?

    How can I read an Excel file and compare if the cells type are numeric or not??
    i hope you can can give me a hand..
    thanks

    If you want to use plsql try utl_file supplied package to read the excel file -> http://psoug.org/reference/utl_file.html
    And you can use a function like this to understand if the column is number or not ;
    CREATE OR REPLACE FUNCTION is_number (
    char_in VARCHAR2)
    RETURN BOOLEAN
    IS
    n NUMBER;
    BEGIN
    n := TO_NUMBER(char_in);
    RETURN TRUE;
    EXCEPTION
    WHEN OTHERS THEN
    RETURN FALSE;
    END is_number;
    DECLARE
    x BOOLEAN;
    BEGIN
    IF is_number('ABC') THEN
    dbms_output.put_line('TRUE');
    ELSE
    dbms_output.put_line('FALSE');
    END IF;
    END;
    /

  • How can I load an external SWF into a movie clip that's inside other movie clip?

    Hi.
    I creating my first flash (actionscript 3.0) website but I'm
    stuck with a visual effect I want to create.
    I have a window on my website called contentWindow. Every
    time you click a button this window is supposed to leave the stage,
    load the requested content and return to the stage.
    The sliding window is a movie clip with 83 frames, 21 to
    enter the stage, 21 to leave the stage again, 20 for nothing (its
    just to simulate the loading time) and 21 to return to the stage.
    Now my goal is, when the user clicks on a navigation button,
    the window exits the stage, loads an external SWF with the content,
    and then returns to the stage.
    I've the "window" movie clip with an instance name of
    "contentWindow". Inside there is another movie clip with an
    instance name of "contentLoader". The content that the user
    requested should appear inside the "contentLoader".
    Now, when the contentWindow leaves the stage, I get this
    error message:
    quote:
    TypeError: Error #1009: Cannot access a property or method of
    a null object reference.
    at rwd_fla::MainTimeline/trigger()
    If I switch
    "contentWindow.contentLoader.addChild(navLoader);" for
    "contentWindow.addChild(navLoader);" it works fine, but the
    external SWF doesn't move with the window.
    How can I load an external SWF into a movie clip that's
    inside other movie clip?

    Hi,
    Recently, I have been putting together a flash presentation.
    And I am just wondering if the following might help you, in your
    communication with the said swf file:
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE,
    onComplete);
    function onComplete(event:Event):void
    event.target.content.thinggy_mc.y -= 100;
    Not the best example, but this allows you to target a mc
    within an external swf file. I think if you look up this code, you
    will have an answer ;)
    Kind Regards,
    Boxing Boom

Maybe you are looking for