.txt file to .xlsx file (600 rows and 40 columns) - c#

I have a program that combines three text files and put them all into one and sorts them all out alphabetically. I was wondering how I could possibly put this onto an excel spreadsheet without downloading and using the excellibrary (if that's possible).
Heres my code that combines all three files if that helps.
private void button1_Click(object sender, EventArgs e) // merge files button
{
System.IO.StreamWriter output = new System.IO.StreamWriter("OUTPUT.txt");
String[] parts = new String[1000];
String[] parts2 = new String[1000];
parts = File.ReadAllLines(textBox1.Text); //gets filepath from top textbox
parts2 = File.ReadAllLines(textBox2.Text); //gets filepath from middle textbox
String[] head = File.ReadAllLines(headingFileBox.Text); //header file array
//merging the two files onto one list, there is no need to merge the header file because no math is being
//computed on it
var list = new List<String>();
list.AddRange(parts);
list.AddRange(parts2);
//foreach loop to write the header file into the output file
foreach (string h in head)
{
output.WriteLine(h);
}
//prints 3 blank lines for spaces
output.WriteLine();
output.WriteLine();
output.WriteLine();
String[] partsComb = list.ToArray(); // string array that takes in the list
Array.Sort(partsComb);
//foreach loop to combine files and sort them by 1st letter
foreach (string s in partsComb)
{
partsComb.Equals(s);
output.WriteLine(s);
}
output.Close();
}
Any help would be much appreciated.

You could look at creating it in a CSV format (Comma-separated values). Excel naturally opens it up and loads the data into the rows and cells.
Basic CSV looks like this:
"Bob","Smith","12/1/2012"
"Jane","Doe","5/10/2004"
Some things are optional like wrapping everything in quotes, but needed if your data may contain the delimiter.

If you're okay with a comma separated values (CSV) file, that's easy enough to generate with string manipulation and will load in Excel. If you need an excel specific format and are okay with XLSX, you can populate one with some XML manipulation and a ZIP library.
Fair warning, you will have to be careful about escaping commas and new lines if you choose a traditional CSV file. There are libraries that handle that as well.

You might want to try Excel package plus: http://EPPlus.codeplex.com
It's free, lightweight, and can create xlsx files.

Related

How to AppendAllText in excel file for multi-variables in multi-columns using c#?

The following code line allows me to append the variable w1 in excel file. but appending process happens in the first column. how to make it for multi-variables {w1, w2, w3} in multi-columns?
File.AppendAllText(Path.Combine(docPath, "Groupbox1.CSV"), w1);
First, you're actually working with .CSV files, not Excel. The CSV stands for Comma Separated Values, so each value in a line of text on these files are typically separated by a comma (or other delimiters such as semicolon). The Excel application lets you open .CSV files, but they are different from Excel files which have either .xls or .xslx extensions. Excel will display values separated by commas in their own columns.
Then, say you have multiple variables. Then you can simply create one string with commas in between values, and write it to the file.
var w1 = "Data1";
var w2 = "Data2";
var w3 = "Data3";
// This creates a string, according to above data, that looks like
// "Data1,Data2,Data3"
var lineToWrite = string.Format("{0},{1},{2}", w1, w2, w3);
File.AppendAllText(Path.Combine(docPath, "Groupbox1.CSV"), lineToWrite);
Now we write that line to the file, and each data item is separated by a comma. Now when you open this with Excel, each data item will be displayed in its own column.

How to write tab-delimited text into excel sheet programmatically?

I have an object of StringBuilder which stores a tab-delimited text and I want to import it to an Excel sheet. In my application it can be achieved in two ways. From a dialog one can choose either copying the text to the clipboard (and then he/she can open a new Excel sheet and simply paste in Excel) or saving it directly to an Excel workbook. First option works perfectly fine and I want to implement the behaviour for saving directly.
The only way that I found on the internet is storing each line of the text to the string array and then each index of array will be new row in Excel sheet, so I can write each row by iterating the array.
for (int i = 0; i < exportStrings.Count; i++)
{
Excel.Range currentRange = (Excel.Range)xlWsh.Cells[i + 1, 1];
currentRange.Value = exportStrings[i];
}
But then it causes a problem for the first option. Since the text is now stored as a string array, I cannot easily copy it to the clipboard. That is why I decided to keep my text stored as a stringbuilder. I also tried to write the text to the very first cell in the Excel sheet, (since it works when I paste the text to first cell in Excel sheet manually in the first option) but it doesn't recognise the new line charactes.
Excel.Range currentRange = (Excel.Range)xlWsh.Cells[1, 1];
currentRange.Value2 = exportStrings.ToString();
Any idea how it can be done using stringbuilder? or how can I make it to recognise new line character?
You can always extract a string from your string builder, and then split it into lines, if you need a string array:
StringBuilder sb = new StringBuilder();
//fill sb with whatever data you need
if (option1)
{
//use stringbuilder, copy to clipboared
}
if (option2)
{
//convert to string array
String allText = sb.ToString();
string[] textLines = allText.Split(Environment.NewLine);
//write to Excel...
}
Admittedly, this is not perfect in terms of efficiency: You are creating an intermediate string, and then you again allocate memory for the string array. But I am going to assume that you are dealing with a limited amount of data, and that the interaction with Excel takes more time anyway than a few object allocations.

C# trouble creating a table in console

I'm struggle to get data to display in a table within a console application. I believe it may be something to-do with the way I am getting the data to display.
I'm using this to read the content of text files:
string currentDir = Directory.GetCurrentDirectory();
string[] textFiles = Directory.GetFiles(currentDir, "*.txt");
string[] lines = new string[11];
for (int i = 0; i < textFiles.Length; i++)
{
lines[i] = File.ReadAllText(textFiles[i]);
}
Then I'm trying to display all the content of the text file into a table, each text file has 600 entries and they all go together to make a table.
Console.WriteLine("{0,10} \t {1,15}", lines[0], lines[1]);
Was my attempt of getting them to display in a table but only the last entry of lines[0] and first entry of lines[1] are being put on the same line in console... Anyone have any ideas?
You're reading the entire contents of a file in a simple string, so that's what you'll get in that string - the contents of the file, including any new lines, tabs, spaces and so on. If you want to manipulate individual bits of strings within those files, you'll need to split those strings according to some rules first.
The formatting alignment you're using doesn't do all that much by itself - see Alignment Component in https://msdn.microsoft.com/en-us/library/txafckwd.aspx

creating a difference file from .csv files

I am creating an application which converts a MS Access table and an Excel sheet to .csv files and then differences the access table with the excel sheet. The .csv files are fine but the resulting difference file has errors in fields that contain html (the access table has fields with the html). I'm not sure if this is a special character issue because the special characters were not an issue in creating the .csv file in the first place, or if it is an issue with the way I am differencing the two files.
Part of the problem I suppose could be that in the access .csv file, the fields that contain the html are formatted so that some of the information is on separate lines instead of all on one line, which could be throwing off the reader, but I don't know how to correct this issue.
This is the code for creating the difference file:
string destination = Form2.destination;
string path = Path.Combine(destination, "en-US-diff.csv");
string difFile = path;
if (File.Exists(difFile))
{
File.Delete(difFile);
}
using (var wtr = new StreamWriter(difFile))
{
// Create the IEnumerable data sources
string[] access = System.IO.File.ReadAllLines(csvOutputFile);
string[] excel = System.IO.File.ReadAllLines(csvOutputFile2);
// Create the query
IEnumerable<string> differenceQuery = access.Except(excel);
// Execute the query
foreach (string s in differenceQuery)
{
wtr.WriteLine(s);
}
}
Physical line versus logical line. One solution is to use a sentinel, which is simply an arbitrary string token selected in such a way so as not to confound the parsing process, for example "##||##".
When the input files are created, add the sentinel to the end of each line...
1,1,1,1,1,1,###||##
Going back to your code, the System.IO.File.ReadAllLines(csvOutputFile); uses the Environment.Newline string as its sentinel. This means that you need to replace this statement with the following (pseudo code)...
const string sentinel = "##||##";
string myString = File.ReadAllText("myFileName.csv");
string[] access = myString.Split(new string[]{sentinel},
StringSplitOptions.RemoveEmptyEntries);
At that point you will have the CSV lines in your 'access' array the way you wanted as a collection of 'logical' lines.
To make things further conformant, you would also need to execute this statement on each line of your array...
line = line.Replace(Environment.NewLine, String.Empty).Trim();
That will remove the culprits and allow you to parse the CSV using the methods you have already developed. Of course this statement could be combined with the IO statements in a LINQ expression if desired.

Writing in an CSV file using C#

I'm looking for a way to write strings in a different cell of a CSV file.
I'm using this program,
private void button1_Click(object sender, EventArgs e)
{
string filePath = #"E:\test.csv";
string a = "a";
string b = "c";
string c = "d";
string d = "d";
File.WriteAllText(filePath, a);
// how can add the other strings in the next cells ?
}
What I need here is to write "a" in the first cell, "b" in the second cell, c ..
CSV is a pretty simple file format, especially if you don't need any cells to contain nested commas. CSV means comma-separated values, so you just need a way to construct a string with commas between each cell. This will work, although it is only for a single line:
File.WriteAllText(filePath, String.Join(",", a, b, c, d));
CSV is absolutely NOT a SIMPLE file format, it is a sufficiently elaborate format that is able to encompass almost any kind of data regardless of shape or size.
The CSV format is capable of dealing with optional parameters vs non optional, data with or without line breaks, and should be able to work with or without field escaping characters in any field without line breaks and is required to have field escaping characters in fields with line breaks.
You should not ever work with CSV files by hand, you should utilize FileHelpers to work with CSV files.
At this point I no longer use FileHelpers as my goto CSV parsing library I use CsvHelper from Josh Close.
If there are only 4 values, and a single row? (Which I assume is not the case?)
string csv = string.Format("{0},{1},{2},{3}\n", a,b,c,d);
File.WriteAllText(filePath, csv);
If the data is based on some sort of collection, give some more info.

Categories