This article describes the method of importing CSV files into Excel workbooks in C#. Share it for your reference. The details are as follows:
You must add a reference to the project: from the .NET tab of the Visual Studio Add Reference dialog box, and the Microsoft Excel 12.0 Object Library (you can use 14.0 if you want, too, but nothing lower).
The C# code is as follows:
using ; using ; /// <summary> /// Takes a CSV file and sucks it into the specified worksheet of this workbook at the specified range /// </summary> /// <param name="importFileName">Specifies the full path to the .CSV file to import</param> /// <param name="destinationSheet"> object corresponding to the destination worksheet.</param> /// <param name="destinationRange"> object specifying the destination cell(s)</param> /// <param name="columnDataTypes">Column data type specifier array. For the property.</param> /// <param name="autoFitColumns">Specifies whether to do an AutoFit on all imported columns.</param> public void ImportCSV(string importFileName, destinationSheet, destinationRange, int[] columnDataTypes, bool autoFitColumns) { ( "TEXT;" + (importFileName), destinationRange, ); [1].Name = (importFileName); [1].FieldNames = true; [1].RowNumbers = false; [1].FillAdjacentFormulas = false; [1].PreserveFormatting = true; [1].RefreshOnFileOpen = false; [1].RefreshStyle = ; [1].SavePassword = false; [1].SaveData = true; [1].AdjustColumnWidth = true; [1].RefreshPeriod = 0; [1].TextFilePromptOnRefresh = false; [1].TextFilePlatform = 437; [1].TextFileStartRow = 1; [1].TextFileParseType = ; [1].TextFileTextQualifier = ; [1].TextFileConsecutiveDelimiter = false; [1].TextFileTabDelimiter = false; [1].TextFileSemicolonDelimiter = false; [1].TextFileCommaDelimiter = true; [1].TextFileSpaceDelimiter = false; [1].TextFileColumnDataTypes = columnDataTypes; ().WriteLog("Importing data..."); [1].Refresh(false); if (autoFitColumns==true) [1].(); // cleanup [1].Delete(); }
How to use it is as follows:
( @"C:\MyStuff\", ()([1]), ()((()[1]).get_Range("$A$7")), new int[] { 2, 2, 2, 2, 2 }, true);
I hope this article will be helpful to everyone's C# programming.