Add column to Excel - c#

using (System.IO.StreamWriter writer = new System.IO.StreamWriter(#"" + textBox2.Text + #"\" + filename.TrimStart() + ".csv", true))
{
if (!exists)
{
writer.WriteLine(DateTime.Now.ToLongDateString());
writer.WriteLine("REG.,BR.,BR.NAME,AC TYPE,PRODUCT,NO.OF ACS,ORG.CURRENCY BALANCE,ORG CURRENCY,BALANCE LKR");
writer.WriteLine(text.Replace("|", ","));
}
writer.WriteLine(text.Replace("|", ","));
////true is append parameter. I use this code to create Excel files. I want add new column and fill each cell with auto increment numbers.

As you didn't include the appropriate infos I take it that text includes all lines that you want to use and , is being used as the separator instead of the more commonly used ; .
The following splits this complete text into multiple lines and creates an "autoincrement" number that is appended as the last column.
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(#"" + textBox2.Text + #"\" + filename.TrimStart() + ".csv", true))
{
if (!exists)
{
writer.WriteLine(DateTime.Now.ToLongDateString());
writer.WriteLine("REG.,BR.,BR.NAME,AC TYPE,PRODUCT,NO.OF ACS,ORG.CURRENCY BALANCE,ORG CURRENCY,BALANCE LKR");
}
var textArray = text.Replace("|", ",").split(Environment.NewLine);
int number = 0;
foreach (string text in textArray)
{
number ++;
write.WriteLine(text + "," + number.ToString());
}

Related

Populating a Textbox with a Text File but it always adds a blank first line?

I have a file containing text and I can get it to populate a textbox on page load but it always adds a blank first line. Any ideas? I've tried skipping the first line in the array in case it was blank (both 0 and 1) but 0 does nothing and 1 skips the first line in the text file.
I've also tried to set the textbox to null and "" first in case it was appending to the textbox in some way.
//Populating the contents box
string[] str = null;
if (File.Exists(docPath + prefix + libIDPath + "\\" + oldFileName))
{
str = File.ReadAllLines(docPath + prefix + libIDPath + "\\" + oldFileName);
//str = str.Skip(0).ToArray();
//FDContentsBox.Text = null;
}
foreach (string s in str)
{
FDContentsBox.Text = FDContentsBox.Text + "\n" + s;
}
In your foreach you are appending the "\n" before appending the string itself. Try
FDContentsBox.Text = FDContentsBox.Text + s + "\n";
instead.
Please try this, there is no need to read all lines nor a foreach loop
var filePath = docPath + prefix + libIDPath + "\\" + oldFileName;
if (File.Exists(filePath))
{
FDContentsBox.Text = File.ReadAllText(filePath);
}

Increment file name by 1 if the file exists in c#

I am trying to increment the filename (e.g., "file1.csv", "file2.csv", etc.), each time a new file is generated. I followed this thread Increment the file name if the file already exists in c# but the solution is not useful for my case. What I want to do is check if the file exists in the first place and if it does write in it. If it doesn't create one and write. The problem is that if the file exists but it's from another user, I want the system to increment the file number and not write to the same file just because it exists. What I have so far:
public void saveFile()
{
int count = 0;
string title = "TimeStamp,Name,Trial,Time_spent-dist,Time_spent_tar\n";
string output = System.DateTime.Now.ToString("mm_ss_ffff") + "," +
currentScene.name.ToString() + "," +
trialNum.ToString() + "," +
timerDistractor.ToString() + "," +
timerTarget.ToString();
string fname = "User_" + count + ".csv";
string path = Path.Combine(Application.persistentDataPath, fname);
if (File.Exists(path))
{
File.AppendAllText(path, "\n" + output);
}
else
{
StreamWriter writer = new StreamWriter(path);
writer.WriteLine(title + "\n" + output);
writer.Close();
}
}
Any pointers?

C# ASP.Net: Read & Rewrite File based on session variables

I am working on a website ATM school project, and I need to be able to rewrite the account balance in the original .txt file based on session transactions. The .txt file contains 3 lines, each with (username),(password),(balance). The issue I'm having is that the program cannot write to file while it is still reading it. The loop works fine if I write to a different file, but I have to edit the original (so the updated balance is retained the next time the program is run). Below is the code from the Logout page load event.
//Stream variable
StreamReader readFile;
StreamWriter writeFile;
//Counter variable
int index = 0;
//Open file
readFile = File.OpenText(#"C:\C#\Project4_TSullivan\loginFile.txt");
//Array rows
const int ROWS = 3;
while (index < ROWS && !readFile.EndOfStream)
{
string str = readFile.ReadLine();
string[] tokens = str.Split(',');
//Check if username matches session username
if (tokens[0] == Convert.ToString(Session["sessionUserName"]))
{
//Update balance
tokens[2] = Convert.ToString(Session["sessionBalance"]);
}
if (index == 0)
{
writeFile = File.CreateText(#"C:\C#\Project4_TSullivan\loginFile.txt");
writeFile.WriteLine(tokens[0] + "," + tokens[1] + "," + tokens[2]);
writeFile.Close();
}
else
{
writeFile = File.AppendText(#"C:\C#\Project4_TSullivan\loginFile.txt");
writeFile.WriteLine(tokens[0] + "," + tokens[1] + "," + tokens[2]);
writeFile.Close();
}
index++;
}
//Close file
readFile.Close();
Please let me know if any additional info would be helpful. I may be going about this in entirely the wrong way, and any advice would be much appreciated. Thanks!
Edited
Here is the solution in case the mods want to save it. Using File.ReadAllLines I was able to store the contents of the file in an array. Then I created 3 more arrays (1 for each line in the file) to tokenize each line.
string path = #"C:\C#\Project4_TSullivan\loginFile.txt";
string[] readFile = File.ReadAllLines(path);
string[] token0 = readFile[0].Split(',');
string[] token1 = readFile[1].Split(',');
string[] token2 = readFile[2].Split(',');
if (token0[0] == Convert.ToString(Session["sessionUsername"]))
{
token0[2] = Convert.ToString(Session["sessionBalance"]);
}
else if (token1[0] == Convert.ToString(Session["sessionUsername"]))
{
token1[2] = Convert.ToString(Session["sessionBalance"]);
}
else
{
token2[2] = Convert.ToString(Session["sessionBalance"]);
}
using (StreamWriter writeFile = File.CreateText(path))
{
writeFile.WriteLine(token0[0] + "," + token0[1] + "," + token0[2]);
writeFile.WriteLine(token1[0] + "," + token1[1] + "," + token1[2]);
writeFile.WriteLine(token2[0] + "," + token2[1] + "," + token2[2]);
}

How to add Column and Row header while appending data into CSV file using C#

I'm trying to insert data into CSV file using C# code. With the code I pasted below, I am able to add column header to the CSV file. But I need to add both column and row header in the CSV file for better readability. Please help me on this.
C# Code
string newFileName = "C:\\AlertReportTill_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".csv";
string AlertDetails = fromDate + "," + toDate + "," + Column1's Value + "," + Column2's Value + ","
+ Column3's Value + "," + Environment.NewLine;
if (!System.IO.File.Exists(newFileName))
{
string AlertHeader = "Weekly Report" + Environment.NewLine + "From Date" + "," + "To Date" + "," +
"ColumnHeader1" + "," + "ColumnHeader2" + "," +
"ColumnHeader3" + "," + Environment.NewLine;
System.IO.File.WriteAllText(newFileName, AlertHeader);
} //End of If Statement
System.IO.File.AppendAllText(newFileName, AlertDetails);
For better clarity, I have added an image below to help you understand my question. It would be very helpful if someone can sort this out for me. Thanks in advance.
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication104
{
class Program
{
static void Main(string[] args)
{
string oldFileName = "C:\\AlertReportTill.csv";
string newFileName = string.Format("C:\\AlertReportTill_{0}.csv", DateTime.Now.ToString("yyyyMMdd_hhmmss"));
StreamReader reader = new StreamReader(oldFileName);
if (!System.IO.File.Exists(newFileName))
{
StreamWriter writer = new StreamWriter(newFileName);
writer.WriteLine("Weekly Report");
string AlertHeader = string.Join(",", new string[]
{"",
"ColumnHeader1", "ColumnHeader2", "ColumnHeader3"
});
writer.WriteLine(AlertHeader);
string line = "";
int RowCount = 0;
while ((line = reader.ReadLine()) != null)
{
List<string> AlertDetails = line.Split(new char[] { ',' }).ToList();
AlertDetails.Insert(0, "RowHeader" + ++RowCount);
writer.WriteLine(string.Join(",", AlertDetails));
}
reader.Close();
writer.Flush();
writer.Close();
} //End of If Statement
}
}
}

c# Windows Form, replace string in textbox (file content) with another string

I have a textbox that contains all of the lines of a loaded file.
It looks like this:
I am able to load a specific line of the file that contains a specific string using this in the app:
How would I be able to update the file/main textbox after I press the "Edit Module" button, if any of the textboxes would be changed .
For example, I would change Exam Weighting: "0.4" to Exam Weighting: "0.6", then press the "Edit Module" button which would edit the main textbox(file content). Which then would allow me to save the file with the updated content.
This is the code I am using to get a specific line from the file based on string from a textbox:
private void editModuleButton_Click(object sender, EventArgs e)
{
citation = editModuleComboBox.Text;
citationChange();
}
private void citationChange()
{
List<string> matchedList = new List<string>();
string[] linesArr = File.ReadAllLines(fileName);
//find matches
foreach (string s in linesArr)
{
if (s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
//output
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
selectedModuleLabel.Text = lineData[2];
moduleTitleTextBox.Text = lineData[3];
creditsTextBox.Text = lineData[4];
semesterTextBox.Text = lineData[5];
examWeightingTextBox.Text = lineData[6];
examMarkTextBox.Text = lineData[7];
testWeightingTextBox.Text = lineData[8];
testMarkTextBox.Text = lineData[9];
courseworkWeightingTextBox.Text = lineData[10];
courseworkMarkTexbox.Text = lineData[11];
}
}
If somebody with enough rep could insert the images to this post, that would be great. Thanks
This solution might not be the perfect, but should work for you. What you need to do is whenever the Edit Module button is pressed, create a new string based on the text fields and replace it with the original line. First declare a string variable private string ChangedString = ""; inside the class, then:
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
string Stream = lineData[0]; //Store this somewhere so that it can be accessed later
string Stage = lineData[1]; //Store this somewhere so that it can be accessed later
selectedModuleLabel.Text = lineData[2];
moduleTitleTextBox.Text = lineData[3];
creditsTextBox.Text = lineData[4];
semesterTextBox.Text = lineData[5];
examWeightingTextBox.Text = lineData[6];
examMarkTextBox.Text = lineData[7];
testWeightingTextBox.Text = lineData[8];
testMarkTextBox.Text = lineData[9];
courseworkWeightingTextBox.Text = lineData[10];
courseworkMarkTexbox.Text = lineData[11];
}
store Stream and Stage in any Textbox/ComboBox if you already haven't then replace them accordingly in the following line. Now in EditButton_Click [Click Event] write:
ChangedString = Stream + "," + Stage + "," + selectedModuleLabel.Text + "," + moduleTitleTextBox.Text
+ "," + creditsTextBox.Text + "," + semesterTextBox.Text + "," + examWeightingTextBox.Text + ","
+ examMarkTextBox.Text + "," + courseworkWeightingTextBox.Text + "," + courseworkMarkTexbox.Text;
Now replace this string with the original line.
Edit: As you would get the line number which is being edited, store it in a variable, let's say
int LineBeingEdited = 3 //Supposing line number three is being edited.
Then again in the same Click event you can write this:
ChangedString = Stream + "," + Stage + "," + selectedModuleLabel.Text + "," + moduleTitleTextBox.Text
+ "," + creditsTextBox.Text + "," + semesterTextBox.Text + "," + examWeightingTextBox.Text + ","
+ examMarkTextBox.Text + "," + courseworkWeightingTextBox.Text + "," + courseworkMarkTexbox.Text;
var lines = TextBox1.Lines;
lines[LineBeingEdited] = ChangedString;
TextBox1.Lines = lines;
EDIT 2: To get the line number I would suggest you to modify your for each loop to for loop. Also add a int variable to store the line number inside the class like : private int LineBeingEdited = 0;
Modify this for each :
foreach (string s in linesArr)
{
if (s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
To for loop:
for (int a = 0; a < linesArr.Length; a++)
{
if (s.Contains(citation))
{
matchedList.Add(linesArr[a]); //matched
LineBeingEdited = a;
break; //breaks the loop when a match is found
}
}
The above method is being used, taking into consideration that there will always be a single match. LineBeingEdited will now have the line number and can be accessed from anywhere in the class

Categories