How can I add 2 cells in a CSV file in WPF? - c#

I use the OpenFileDialog in my WPF program to give the user the option to select a .csv file and read it into the program. Now I have the path and everything from the file that the user wants and now I want to add 2 more cells to the Excel file after a button click. How should I change it so that as soon as the button is pressed, 2 columns and cells are added to the previously imported Excel file. Here is my OpenFileDialog how I get the file OpenFileDialog::
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.Filter = "CVS (*.cvs)|*.csv|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
openFileDialog.Title = "CVS Datei Auswählen zum Konvertieren";
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
{
tbxFiles.Items.Add(System.IO.Path.GetFileName(filename));
string temp;
var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
temp = streamReader.ReadToEnd();
test = temp;
}
}
}
SaveFileDialog:
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "CVS (*.cvs)|*.csv|All files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
List<String> liste = new List<String>();
// test = test + "Hallo;";
//File.WriteAllText(dialog.FileName, test);
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(test);
while ((line = file.ReadLine()) != null)
{
if (counter == 0)
{
line += ",column1,column2";
}
else
{
line += $",{""},{""}";
}
counter++;
}
file.Close();
}
In my "test" string I have now read in what is in the cvs file via streamreader. This is what the cvs Header looks like:
Picture 1
and so how i want it look like after my C# change:
Picture2
tbxFiles = my TextBox where the path of the selected file is shown.
So how can I add additional Excel columns with associated cells to the imported Excel file in Code Behind 2?

There you go:
....
while ((line = file.ReadLine()) != null)
{
if (counter == 0)
{
line += ",column1,column2";
}
else
{
line += $",{value1},{value2}";
}
counter++;
}
...

Related

How to link users file selection to a StringSplit

I'm trying to get the users chosen file to split into an array which is separated by , and /t.
The user can choose a file at the top of the code but how do I get their choice to split into an array lower down when they press the ValidateButton
The text file or ordered in this way
info,info,info,
info,info,info,
info,info,info,
If I can get them into an array then I can easily organises the data.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\"; // Start in C: drive
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.RestoreDirectory = true;
openFileDialog1.DefaultExt = "txt"; // Extension of file is txt
openFileDialog1.Filter = "Text|*.txt||*.*"; //Only text files
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileNameBox.Text = openFileDialog1.FileName; // Chosen file name is displayed in text box
var fileStream = openFileDialog1.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
var fileContent = reader.ReadToEnd();
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//This is the file path the user has chosen
}
public void ValidateButton_Click(object sender, EventArgs e)
{
//Call Multi line text box
//Call PROGRESS BAR_
int counter = 0;
string lines;
string Patient = lines;
string[] split = Patient.Split(new Char[] { ',', '\t' });
foreach (string s in split)
if (s.Trim() != "")
Console.WriteLine(s);
{
Console.WriteLine(lines);
counter++;
}
Console.WriteLine("There were {0} records.", counter);
Console.ReadKey();
}
List<string> temp = new List<string>();
string[] finalArray;
using (StreamReader reader = new StreamReader(fileStream))
{
// We read the file then we split it.
string lines = reader.ReadToEnd();
string[] splittedArray = lines.Split(',');
// We will check here if any of the strings is empty (or just whitespace).
foreach (string currentString in splittedArray)
{
if (currentString.Trim() != "")
{
// If the string is not empty then we add to our temporary list.
temp.Add(currentString);
}
}
// We have our splitted strings in temp List.
// If you need an array instead of List, you can use ToArray().
finalArray = temp.ToArray();
}

How to create the zip file from the selected rows of datagridview in c#

I am displaying certain elements from .xml files into a DataGridView and it's working fine.
Here is the code to select the xml files
//Browse Folder
private void Btn_SelectFolder_Click(object sender, EventArgs e)
{
try
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK)
{
DataTable dt = new DataTable();
dt.Rows.Clear();
dt.Columns.Add("Select", typeof(bool));
dt.Columns.Add("File_Name");
dt.Columns.Add("Vendor_Name");
dt.Columns.Add("Vendor_ID");
dt.Columns.Add("Date_Range", typeof(DateTime));
lbl_Path.Text = fbd.SelectedPath;
string[] files = Directory.GetFiles(fbd.SelectedPath, "*.xml");
XmlDocument doc = new XmlDocument();
XmlNodeList nodes = doc.GetElementsByTagName("cfdi:Emisor");
XmlNodeList nodes1 = doc.GetElementsByTagName("cfdi:Comprobante");
foreach (string tot_file in files)
{
doc.Load(tot_file);
string FileName = Path.GetFileNameWithoutExtension(tot_file);
for (int i = 0; i < nodes.Count; i++)
{
string Name = nodes[i].Attributes["Nombre"].Value;
string ID = nodes[i].Attributes["Rfc"].Value;
string Date = nodes1[i].Attributes["Fecha"].Value;
DataRow row = dt.NewRow();
row["File_Name"] = FileName;
row["Vendor_Name"] = Name;
row["Vendor_ID"] = ID;
row["Date_Range"] = Date;
dt.Rows.Add(row);
}
}
XML_Grid.DataSource = dt;
txt_FileName.ReadOnly = false;
txt_Name.ReadOnly = false;
txt_ID.ReadOnly = false;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Now what i want is to select the rows from DataGridView and create the zip file of selected files.
I have tried this code to create the zip file:
//Create Zip
private void Btn_SaveZip_Click(object sender, EventArgs e)
{
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string folderToZip = lbl_Path.Text;
string zipFile = saveFileDialog1.FileName + ".zip";
using (ZipArchive zipArchive = ZipFile.Open(zipFile, ZipArchiveMode.Create))
{
DirectoryInfo di = new DirectoryInfo(folderToZip);
FileInfo[] filesToArchive = di.GetFiles();
if (filesToArchive != null && filesToArchive.Length > 0)
{
foreach (FileInfo fileToArchive in filesToArchive)
{
zipArchive.CreateEntryFromFile(fileToArchive.FullName, fileToArchive.Name, CompressionLevel.Optimal);
}
}
}
MessageBox.Show("Zip File Successfully Created", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Question);
}
}
The above code is working fine and creating zip file But it's directly checking the files from the path and creating zip file of that folder.
How to select the files from DataGridview not directly from the folder and create the zip file of selected files.
My Form:
Any help would be helpful for me, I've been trying to get this working for hours now.
If I understood your problem correctly, you want to save only those files where the Select column is checked in your data grid into one zip file.
If so, the following modification to your Zip save routine can help you with that:
using (ZipArchive zipArchive = ZipFile.Open(zipFile, ZipArchiveMode.Create))
{
List<FileInfo> filesToArchive = new List<FileInfo>();
DirectoryInfo di = new DirectoryInfo(folderToZip);
// loop through all of the rows in the data grid
foreach (DataGridViewRow row in XML_Grid.Rows)
{
DataRowView rowView = row.DataBoundItem as DataRowView;
if (rowView == null) continue; // new row or not bound, ignore
var selectedValue = rowView["Select"]; // get the value for the select column
if (selectedValue == DBNull.Value || selectedValue == null || !(bool)selectedValue) // ignore null or false
continue;
string fileName = rowView["File_Name"].ToString(); // get the file name
var files = di.GetFiles(fileName + ".*"); // we had no extension so search the folder to get the full path
filesToArchive.AddRange(files); // add those file(s) to the list to archive
}
if (filesToArchive != null && filesToArchive.Count > 0)
{
foreach (FileInfo fileToArchive in filesToArchive)
{
zipArchive.CreateEntryFromFile(fileToArchive.FullName, fileToArchive.Name, CompressionLevel.Optimal);
}
}
}

Save Opened Text File to Original Location

I am creating an application that will allow me to open a .txt file and edit the values (weight=60, height =50, etc) in a DataGridView. My issue is that I am able to upload the .txt file using OpenFileDialog but am unable to write over and save it in it's previous location.
For clarification, here is my method to upload text files:
private void btnUpload_Click(object sender, EventArgs e)
{
Stream myStream;
openFileDialog1.FileName = string.Empty;
openFileDialog1.InitialDirectory = "C:\\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var compareType = StringComparison.InvariantCultureIgnoreCase;
var fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
var extension = Path.GetExtension(openFileDialog1.FileName);
if (extension.Equals(".txt", compareType))
{
try
{
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(openFileDialog1.FileName);
StreamReader reader = new StreamReader(openFileDialog1.FileName);
string line;
while ((line = reader.ReadLine()) != null)
{
string[] words = line.Split('=');
paramList.Add(new Parameter(words[0], words[1]));
}
BindGrid();
}
}
And what I've tried to save the file:
public void WriteToTextFile(DataGridView dgvParam)
{
String file_name = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
using (StreamWriter objWriter = new StreamWriter(openFileDialog1.FileName))
{
for (Int32 row = 0; row < dgvParam.Rows.Count - 1; row++)
{
StringBuilder sb = new StringBuilder();
for (Int32 col = 0; col < dgvParam.Rows[row].Cells.Count; col++)
{
if (!String.IsNullOrEmpty(sb.ToString()))
sb.Append("="); //any delimiter you choose
sb.Append(dgvParam.Rows[row].Cells[col].Value.ToString().ToUpper());
}
objWriter.WriteLine(sb.ToString());
}
}
It says it is openFileDialog is currently in use and it cannot reach it! Any suggestions or recommendations would be really appreciated!
You need to dispose your reader variable.
You should get rid of the first using statement entirely and wrap that in a using statement instead.

How do I check if one of the lines already exist in the text file?

string filename = "";
private void openToolStripMenuItem1_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = #"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
lines = File.ReadAllLines(RecentFiles);
filename = theDialog.FileName;
for (int i = 0; i < lines.Length; i++)
{
recentfiles = new StreamWriter(RecentFiles, true);
recentfiles.WriteLine(theDialog.FileName);
recentfiles.Close();
items = File
.ReadLines(RecentFiles)
.Select(line => new ToolStripMenuItem()
{
Text = line
})
.ToArray();
recentFilesToolStripMenuItem.DropDownItems.AddRange(items);
}
TextFileContentToRichtextbox(filename);
}
}
I'm not sure if doing the for loop over the lines is right.
But what I want to do is when I open a new text file to check if it already exists in the RecentFiles(RecentFiles.txt) and if it does exist don't write it again.
Loop over lines and if after looping over all the lines and the variable filename does not exist then write it to the text file, and update the items.
Linq is perfect for this:
// if there are not any lines that equal the filename
if (!lines.Any(line => line.Equals(filename)))
{
// then write it into recent files text file
}
//// the below code will work only if a line has 1 fileName with extension or any text.
if (lines.Contains(filename, StringComparer.OrdinalIgnoreCase))
{
//// lines contains
}
else
{
////lines doesnot contain file name
}
Verify whether it full fill your requirement.

EPPlus To Read 1st Column Of Excel Into Array

Use OpenFileDialogwith EPPlus. I get a compile error of:
The name 'sheet' does not exist in the current context
Now, the obvious issue is how do I associate the selected Excel file with my EPPPlus & 2 what do I do to remove the error above?
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
private void btn_ReadExcelToArray_Click(object sender, EventArgs e)
{
fd.Filter = "Excel Files|*.xlsx";
fd.InitialDirectory = #"C:\";
if (fd.ShowDialog() == DialogResult.OK)
{
var columnimport = sheet.Cells["A2:A"];
foreach (var cell in columnimport)
{
var column1CellValue = cell.GetValue<string>();
}
}
}
You are pretty close. All you have to do is create the package based on the stream (or you could use the fileinfo overload - either way). Like this:
var fd = new OpenFileDialog();
fd.Filter = "Excel Files|*.xlsx";
fd.InitialDirectory = #"C:\Temp\";
if (fd.ShowDialog() == DialogResult.OK)
{
using (var package = new ExcelPackage(fd.OpenFile()))
{
var sheet = package.Workbook.Worksheets.First();
var columnimport = sheet.Cells["A2:A"];
foreach (var cell in columnimport)
{
var column1CellValue = cell.GetValue<string>();
}
}
}

Categories

Resources