EPPlus To Read 1st Column Of Excel Into Array - c#

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>();
}
}
}

Related

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

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++;
}
...

How to open only a .dat file. In C#

I'm trying to open a file but I want it filter out to only .dat file.
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
result = fileChooser.ShowDialog();
fileName = fileChooser.FileName; //Get file name.
fileChooser.Filter = "Data File|*.dat;";
fileChooser.DefaultExt = "dat";
fileChooser.AddExtension = true;
}
When having a OpenFileDialog in "using" the filter, defaultExt and Addextension doesn't work.
You should set filters before the call of "ShowDialog" method.
This should work.
using (var fileChooser = new OpenFileDialog())
{
// define the filters (first description | first filter; second description ...
fileChooser.Filter = "Data File|*.dat";
// select the first filter
fileChooser.FilterIndex = 1;
fileChooser.DefaultExt = "dat";
fileChooser.AddExtension = true;
// show the Opendialog
if (fileChooser.ShowDialog() == DialogResult.OK)
{
// get the path of specified file
var filename = fileChooser.FileName;
// use the filename to open the file...
}
}

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.

faster method to import data from text file

I have to import data from a text file to a flat file database. I'm sure there's a faster way to load all the data into the database but I don't know how.
private void ImportButton_Click(object sender, EventArgs e)
{
string Path = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Text File|*.txt";
ofd.ShowDialog();
if (ofd.FileName == string.Empty) return
Path = ofd.FileName;
string data;
using (var sr = new StreamReader(Path))
{
data = sr.ReadToEnd();
}
var items = data.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
var count = 0;
foreach (var info in items.Select(ItemInfo.FromText).Where(info => info != null))
{
count++;
info.Index = ++Envir.ItemIndex;
Envir.ItemInfoList.Add(info);
}
MessageBox.Show(count + " Items have been imported");
UpdateInterface(true);
}
If you're doing this via C#, then I'd recommend SqlBulkCopy. I provided a similar answer to another question a while back. See that link for an example of how I've implemented it in the past.
If you want to know other options available to you then MSDN has quite a good list of options in their data loading guide; http://msdn.microsoft.com/en-us/library/dd425070(v=sql.100).aspx

Categories

Resources