How to import into a template excel file (C#) - c#

I have the code below to save data into a excel file(.csv).
private void SavedataToolStripMenuItem_Click(object sender, EventArgs e)
{
now_status.Text = "save data to excel";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{[![enter image description here][1]][1]
selectedFileName = saveFileDialog1.FileName + ".csv";
System.Text.Encoding enc = System.Text.Encoding.GetEncoding("Shift_JIS");
System.IO.StreamWriter sr = new System.IO.StreamWriter(selectedFileName, false, enc);
int rowCountA = int.Parse(objA_n.Text);
int rowCountB = int.Parse(objB_n.Text);
string field;
field = "Saved Data" + "\r\n" + "Numb,Time(S),AX,AY,BX,BY" + "\r\n";
sr.Write(field);
for (int i = 1; i < rowCountA + 1; i++)
{
string fieldA;
fieldA = "A" + dn_objA[i].ToString() + "," + dtime_objA[i].ToString() + "," + dx_objA[i].ToString() + "," + dy_objA[i].ToString() + ",," + "\r\n";
sr.Write(fieldA);
}
for (int i = 1; i < rowCountB + 1; i++)
{
string fieldB;
fieldB = "B" + dn_objB[i].ToString() + "," + dtime_objB[i].ToString() + ",,," + dx_objB[i].ToString() + "," + dy_objB[i].ToString() + "\r\n";
sr.Write(fieldB);
}
sr.Close();
sr.Close();
}
}
This Generates a simple excel file like this below. Object values will be inserted below the second row.
Is there a way to do the same thing, but into a template excel file? I have an excel file like the one below.
I would like the imported data to show on the left hand side of the excel file.
Also, I want to use macros that I made in the second excel file shown.

Related

C# Deserialize lists within a .dat file to a text box

I have created an application that will save lists to a .dat file using a binary formatter and serializing the list.
I wish to then de serialize this list and display this within a text box.
Furthermore, I have tried using a for each loop to get every object from the list, but it won't continue through the rest of the lists and stops at the first list stored within the file.
I have been tasked with binary formatter even though Ive been informed its obsolete.
`public InPerson(int iId, string sDate, string sTime, string sDuration, string sPatientname, string
sPhonenumber, string sDoctorid, string sRoomnumber, string sNurseid)
{
this.iId = iId;
this.sDate = sDate;
this.sTime = sTime;
this.sDuration = sDuration;
this.sPatientname = sPatientname;
this.sPhonenumber = sPhonenumber;
this.sDoctorid = sDoctorid;
this.sRoomnumber = sRoomnumber;
this.sNurseid = sNurseid;
}
//To String method for saving
public override string ToString()
{
return "In Person Apppointment: " + iId + System.Environment.NewLine +
"Date: " + sDate + System.Environment.NewLine +
"Time: " + sTime + System.Environment.NewLine +
"Duration: " + sDuration + System.Environment.NewLine +
"Patients Name: " + sPatientname + System.Environment.NewLine + "Patients Number: " + sPhonenumber + System.Environment.NewLine +
"Doctors ID: " + sDoctorid + System.Environment.NewLine +
"Room Number: " + sRoomnumber + System.Environment.NewLine +
"Nurse id: " + sNurseid + System.Environment.NewLine + "";
}
InPerson NewInPersonApp = new InPerson(Convert.ToInt32(txtID.Text), dateTimePickerBooking.Text, txtTime.Text, txtDuration.Text, txtPatientName.Text, txtPhoneNumber.Text, txtDoctorID.Text, txtRoomAllocated.Text, txtNurseID.Text);
List<InPerson> InPersonList = new List<InPerson>();
InPersonList.Add(NewInPersonApp);
const String filename = "appointments.dat";
FileStream outFile;
BinaryFormatter bFormatter = new BinaryFormatter();
outFile = new FileStream(filename, FileMode.Append, FileAccess.Write);
bFormatter.Serialize(outFile, InPersonList);
outFile.Close();`
`
I wish to use this code to loop every list out from the file.
`InPersonList = (List<InPerson>)bFormatter.Deserialize(inFile);
foreach (InPerson a in InPersonList)
{
txtBookings.Text += a.ToString();
}`

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

prepend headers to my csv file

I want to prepend headers to my CSV File as to let the data reflect the headings. How would I go about this without having to add it each time writing to the file? Meaning I only want the headers added once on each export. When am exporting to the same file name it should not create duplicates of the same headers. Here is my code below which writes to file:
private void button6_Click_2(object sender, EventArgs e)
{
int count_row = dataGridView1.RowCount;
int count_cell = dataGridView1.Rows[0].Cells.Count;
MessageBox.Show("Please wait while " +comboBox5.Text+ " table is being exported..");
for (int row_index = 0; row_index <= count_row - 2; row_index++)
{
for (int cell_index = 1; cell_index <= count_cell - 1; cell_index++)
{
textBox8.Text = textBox8.Text + dataGridView1.Rows[row_index].Cells[cell_index].Value.ToString() + ",";
}
textBox8.Text = textBox8.Text + "\r\n";
}
System.IO.File.WriteAllText("C:\\Users\\jdavis\\Desktop\\"+comboBox5.Text+".csv", textBox8.Text);
MessageBox.Show("Export of " +comboBox5.Text+ " table is complete!");
textBox8.Clear();
}
Updated attempt:
private void button6_Click_2(object sender, EventArgs e)
{
int count_row = dataGridView1.RowCount;
int count_cell = dataGridView1.Rows[0].Cells.Count;
MessageBox.Show("Please wait while " + comboBox5.Text + " table is being exported..");
if (!File.Exists(comboBox5.Text))
{
string rxHeader = "Code" + "," + "Description" + "," + "NDC" + "," + "Supplier Code"
+ "," + "Supplier Description" + "," + "Pack Size" + "," + "UOM" + Environment.NewLine;
for (int row_index = 0; row_index <= count_row - 2; row_index++)
{
for (int cell_index = 1; cell_index <= count_cell - 1; cell_index++)
{
textBox8.Text = textBox8.Text + dataGridView1.Rows[row_index].Cells[cell_index].Value.ToString() + ",";
}
textBox8.Text = textBox8.Text + "\r\n";
}
System.IO.File.WriteAllText("C:\\Users\\jdavis\\Desktop\\" + comboBox5.Text + ".csv", textBox8.Text);
MessageBox.Show("Export of " + comboBox5.Text + " table is complete!");
textBox8.Clear();
}
}
I really want to try and achieve it without SteamWriter, where am I going wrong?
private void button6_Click_2(object sender, EventArgs e)
{
int count_row = dataGridView1.RowCount;
int count_cell = dataGridView1.Rows[0].Cells.Count;
string path = "C:\\Users\\jdavis\\Desktop\\" + comboBox5.Text + ".csv";
string rxHeader = "Code" + "," + "Description" + "," + "NDC" + "," + "Supplier Code"
+ "," + "Supplier Description" + "," + "Pack Size" + "," + "UOM";
MessageBox.Show("Please wait while " + comboBox5.Text + " table is being exported..");
for (int row_index = 0; row_index <= count_row - 2; row_index++)
{
for (int cell_index = 1; cell_index <= count_cell - 1; cell_index++)
{
textBox8.Text = textBox8.Text + dataGridView1.Rows[row_index].Cells[cell_index].Value.ToString() + ",";
}
textBox8.Text = textBox8.Text + "\r\n";
if (!File.Exists(path))
{
System.IO.File.WriteAllText(path, rxHeader);
System.IO.File.WriteAllText(path, textBox8.Text);
}
else
{
System.IO.File.AppendAllText(path, textBox8.Text);
MessageBox.Show("Export of " + comboBox5.Text + " table is complete!");
textBox8.Clear();
}
}
}
Here is the short version that will even properly handle values that contain , and ":
dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
dataGridView1.RowHeadersVisible = false; // the row headers column is copied too if visible
dataGridView1.SelectAll(); // only the selected cells are used (the Windows Clipboard is not used)
DataObject dataObject = dataGridView1.GetClipboardContent(); // 4 Data Formats: Text,Csv,HTML Format,UnicodeText
File.WriteAllText("1.csv", dataObject.GetData("Csv") as string); // DataFormats.CommaSeparatedValue = "Csv"
//string html = Encoding.ASCII.GetString((dataObject.GetData("HTML Format") as MemoryStream).ToArray()); // just the HTML Clipboard Format is in a MemoryStream
This is my suggested solution.
My suggestion is to first check if the file exists or not, to then decide if you need to write the header or not.
private void DoTheWork(int fileIDtoUpdate)
{
//this is just my representation of what probably already exist in your project
string textInTheTextBox = "blah blah blah blah\nI love text\nI love code\nI love to Code\ndon't you just love to code!";
string filePath1 = #"M:\StackOverflowQuestionsAndAnswers\40726017\File1.txt";
string filePath2 = #"M:\StackOverflowQuestionsAndAnswers\40726017\File2.txt";
string filePath3 = #"M:\StackOverflowQuestionsAndAnswers\40726017\File3.txt";
string filePath4 = #"M:\StackOverflowQuestionsAndAnswers\40726017\File4.txt";
string fileToWorkWith = string.Empty;
//decide which file to work with
switch (fileIDtoUpdate)
{
case 1:
fileToWorkWith = filePath1;
break;
case 2:
fileToWorkWith = filePath2;
break;
case 3:
fileToWorkWith = filePath3;
break;
case 4:
fileToWorkWith = filePath4;
break;
default:
break;
}
//check if the file existed
bool fileExisted = File.Exists(fileToWorkWith);
using (StreamWriter sw = new StreamWriter(fileToWorkWith, true))
{
if (!fileExisted)
{
//if the file did not exist, then you need to put your header line!
sw.WriteLine("Write your Header Line here");
}
sw.WriteLine(textInTheTextBox);//down here... who cares if the file existed or not, you need to append this text to it no matter what!
}
}
Got the answer by simply editing my code with this snippet:
if (!File.Exists(path))
{
System.IO.File.WriteAllText(path, rxHeader + textBox8.Text);
}
else
{
System.IO.File.AppendAllText(path, textBox8.Text);
MessageBox.Show("Export of " + comboBox5.Text + " table is complete!");
textBox8.Clear();
}
for (int row_index = 0; row_index <= count_row - 2; row_index++)
{
textBox8.Text = textBox8.Text + "\r\n";
for (int cell_index = 1; cell_index <= count_cell - 1; cell_index++)
{
textBox8.Text = textBox8.Text + dataGridView1.Rows[row_index].Cells[cell_index].Value.ToString() + ",";
}
}
Just go to the property pannel of textBox8. Text and add column header with comma and set the textbox8 visibility to hidden.

Using streamwriter but file is always empty

I'm using Streamwriter to save my list data to a text file, but the file is always empty when I open it.
I can get the list to display all of the inputs, so the list works. Heres the code for the filewriter.
private void SaveToFile()
{
string taxpayerLine;
string taxpayerFile;
string myFileName;
FileInfo myFile;
SaveFileDialog taxpayerFileChooser;
StreamWriter fileWriter;
taxpayerFileChooser = new SaveFileDialog();
taxpayerFileChooser.Filter = "All text files|*.txt";
taxpayerFileChooser.ShowDialog();
taxpayerFile = taxpayerFileChooser.FileName;
taxpayerFileChooser.Dispose();
fileWriter = new StreamWriter(taxpayerFile, true);
foreach (Taxpayer tp in Taxpayers)
{
taxpayerLine = tp.Name + "," +
tp.Salary.ToString() + "," +
tp.InvestmentIncome.ToString() + "," +
(tp.InvestmentIncome + tp.Salary).ToString() + "," +
tp.GetRate().ToString() + "," +
tp.GetTax().ToString();
fileWriter.WriteLine(taxpayerLine);
}
fileWriter.Close();
fileWriter.Dispose();
myFile = new FileInfo(taxpayerFile);
myFileName = myFile.Name;
MessageBox.Show("Data Saved to " + myFileName);
}
You can try changing your code like this:
private void SaveToFile()
{
string taxpayerLine;
string taxpayerFile = string.Empty;
string myFileName;
FileInfo myFile;
using (SaveFileDialog taxpayerFileChooser = new SaveFileDialog())
{
taxpayerFileChooser.Filter = "All text files|*.txt";
if (DialogResult.OK == taxpayerFileChooser.ShowDialog())
{
taxpayerFile = taxpayerFileChooser.FileName;
}
}
if (!string.IsNullOrEmpty(taxpayerFile))
{
using (StreamWriter fileWriter = new StreamWriter(taxpayerFile, true))
{
foreach (Taxpayer tp in Taxpayers)
{
taxpayerLine = tp.Name + "," +
tp.Salary.ToString() + "," +
tp.InvestmentIncome.ToString() + "," +
(tp.InvestmentIncome + tp.Salary).ToString() + "," +
tp.GetRate().ToString() + "," +
tp.GetTax().ToString();
fileWriter.WriteLine(taxpayerLine);
}
}
myFile = new FileInfo(taxpayerFile);
myFileName = myFile.Name;
MessageBox.Show("Data Saved to " + myFileName);
}
else
{
MessageBox.Show("Data not saved");
}
}
The using statement explicit calls the Dispose() method of disposable objects after the block execution. http://msdn.microsoft.com/en-us/library/yh598w02.aspx

C# streamwriter create part of files

I am trying to create a hash text file. The code works, the problem is that once the streamwriter starts the process it won't stop until it is finished. I want to break up the output file into smaller parts. How do I stop the streamwriter and start a new file without starting the process over again?
string infile = #"ntlmchar.txt";
string hashfile = #"ntlmhash.txt"; //File that includes the hash and clear test
string charfile = #"ntlmchar.txt"; //File that only has the clear text
string oldCharFile = ""; //Temp file to apply to infile.
int cint = 1; //The number of characters in the file
string str_cint = cint.ToString(); //convert cint to string
int pint = 1; //The number of parts to the character file
string str_pint = pint.ToString(); //convert pint to string
int cm = 4; //Max number of characters
int pm = 4000; //Man number of parts
int line = 0; //line index number
while (cint <= cm)
{
if (!File.Exists(infile))
{
for (int ci =1; ci <= cm; ci++)
{
str_cint = cint.ToString();
for (int pi =1; pi <= pm; pi++)
{
str_pint = pint.ToString();
// System.Console.WriteLine("Inner for loop cint file does not exist" +cint +" pint " + pint);
// System.Console.WriteLine("Inner for loop str_cint file does not exist " + str_cint + " cint " + cint);
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
pint = pi;
oldCharFile = charfile;
infile = oldCharFile;
if (File.Exists(infile)) break;
// System.Console.WriteLine("inner loop file " + infile);
}
// System.Console.WriteLine("outer for loop cint " + cint + " pint " + pint);
// System.Console.WriteLine("infile not found " + infile + " " + oldCharFile + " " + charfile + " " + hashfile);
}
// System.Console.WriteLine("No work files found " + infile + " " + oldCharFile + " " + charfile + " " + hashfile);
}
else if (File.Exists(infile))
{
// Create a file to write to.
// System.Console.WriteLine("cint at the start of else if " + cint + " str_cint " + str_cint);
infile = oldCharFile;
str_cint = cint.ToString();
// System.Console.WriteLine("cint after assign to str_cint " + cint + " str_cint " + str_cint);
pint=1;
str_pint = pint.ToString();
hashfile = "ntlmhash" + str_cint + "_" + str_pint + ".txt";
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
//System.Console.WriteLine(infile + " " + oldCharFile + " " + charfile + " " + hashfile);
// System.Console.WriteLine("Infile found " + cint + " " + pint);
using (StreamWriter h = new StreamWriter(hashfile))
using (StreamWriter c = new StreamWriter(charfile))
using (StreamReader sr = new StreamReader(infile))
{
string i = "";
while ((i = sr.ReadLine()) != null)
{
foreach (string s in alpha)
{
if (line <= 2000000)
{
string j = i + s;
string str = Program.Ntlm(j);
hashfile = "ntlmhash" + str_cint + "_" + str_pint + ".txt";
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
// System.Console.WriteLine("line before writing to file " + line + " in charfile " + charfile);
h.WriteLine("{0}, {1}", j, str);
c.WriteLine("{0}", j);
line++;
// System.Console.WriteLine("h file" + h + " c file" + c);
}
else
{
h.Flush();
c.Flush();
pint++;
str_pint = pint.ToString();
hashfile = "ntlmhash" + str_cint + "_" + str_pint + ".txt";
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
line = 1;
System.Console.WriteLine("line after writing to part of file " + line + " in charfile " + charfile);
}
}
}
I assume you're trying to get 2,000,000 items per file? You just need to restructure a little.
Right now you have:
using (StreamWriter h = new StreamWriter(hashfile))
using (StreamWriter c = new StreamWriter(charfile))
using (StreamReader sr = new StreamReader(infile))
{
string i = "";
while ((i = sr.ReadLine()) != null)
{
You need to change your code so that you open the output files later:
using (StreamReader sr = new StreamReader(infile))
{
StreamWriter h = null;
StreamWriter c = null;
try
{
h = new StreamWriter(...);
c = new StreamWriter(...);
string i = "";
while ((i = sr.ReadLine()) != null)
{
// output line here
// and increment line counter.
++line;
if (line > 2000000)
{
// Close the output files and open new ones
h.Close();
c.Close();
h = new StreamWriter(...);
c = new StreamWriter(...);
line = 1;
}
}
}
finally
{
if (h != null) h.Close();
if (c != null) c.Close();
}
}

Categories