i am creating VSTO in excel , for this i am converting the existing macro to c# where have to find minimun of the column , i have converted this far as shown below :
using Microsoft.Office.Tools.Ribbon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using Microsoft.Office.Interop.Excel;
namespace CpCpk
{
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
var excelApp = Globals.ThisAddIn.Application.ActiveSheet;
//excelApp.Workbooks.Add();
excelApp.Range["P2"].Select();
excelApp.ActiveCell.FormulaR1C1 = "=MIN(C[-14])";
excelApp.Range["Q2"].Select();
excelApp.Visible = true;
}
}
}
now i am not getting any error in syntax , but during execution i am getting below rror:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.__ComObject' does not contain a definition for 'ActiveCell''
in the line :
excelApp.ActiveCell.FormulaR1C1 = "=MIN(C[-14])";
somebody please help me how to correct this..
You need to set FormulaR1C1 directly from specific cell
excelApp.Range["P2"].FormulaR1C1 = "=MIN(C[-14])";
You could just convert the spreadsheet to a datatable via closed xml (via nuget) like so:
public static DataTable GetDataFromExcel(string path, dynamic worksheet)
{
//Save the uploaded Excel file.
DataTable dt = new DataTable();
//Open the Excel file using ClosedXML.
using (XLWorkbook workBook = new XLWorkbook(path))
{
//Read the first Sheet from Excel file.
IXLWorksheet workSheet = workBook.Worksheet(worksheet);
//Create a new DataTable.
//Loop through the Worksheet rows.
bool firstRow = true;
foreach (IXLRow row in workSheet.Rows())
{
//Use the first row to add columns to DataTable.
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
if (!string.IsNullOrEmpty(cell.Value.ToString()))
{
dt.Columns.Add(cell.Value.ToString());
}
else
{
break;
}
}
firstRow = false;
}
else
{
int i = 0;
DataRow toInsert = dt.NewRow();
foreach (IXLCell cell in row.Cells(1, dt.Columns.Count))
{
try
{
toInsert[i] = cell.Value.ToString();
}
catch (Exception ex)
{
}
i++;
}
dt.Rows.Add(toInsert);
}
}
return dt;
}
Then get the minimum via linq:
var min = dt.AsEnumerable()
.Min(r => r.Field<Decimal>(col));
Reminder, you'll need using System.Linq; and using ClosedXML.Excel;
Related
I have a problem with messagebox.
Form1:
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
Class1 excel = new Class1(dialog.FileName, 1);
string path = dialog.FileName + ".txt";
TextWriter tw = new StreamWriter(path, true);
tw.Write(excel.ReadCell(0, 0));
tw.Close();
}
}
}
}
Class1:
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
class Class1
{
string path = "";
_Application excel = new _Excel.Application();
Workbook wb;
Worksheet ws;
private object excelWorksheet;
public Class1(string path, int Sheet)
{
this.path = path;
wb = excel.Workbooks.Open(path);
ws = (Worksheet)wb.Worksheets[Sheet];
}
public string ReadCell(int row, int column)
{
column += 1;
do
{
row++;
if(((_Excel.Range)ws.Cells[row, column]).Value2 == null)
break;
_Excel.Range range = (_Excel.Range)ws.Cells[row, column];
if (range.Value.ToString() == "Z_KomSilnice_L (24200)/7")
{
range = (_Excel.Range)ws.Cells[row, column + 1];
return range.Value.ToString();
}
else
{
MessageBox.Show("Hodnota nenalezena!");
}
} while (true);
return "";
}
}
}
When I write the code like this, the messagebox always appears.
But I would need him to show up only if the value is not in the excel file.
if (range.Value.ToString() == "Z_KomSilnice_L (24200)/7")
{
range = (_Excel.Range)ws.Cells[row, column + 1];
return range.Value.ToString();
}
else
{
MessageBox.Show("Hodnota nenalezena!");
}
The problem is this checks the first cell, finds that the value is not found and writes a messagebox.
So I know where the problem is and why the problem is, but I don't know how to combine it to make it work.
Thank you all for the advice.
If I understand correctly;
You're returning if you find the value already, so instead of giving same message when every column is read in the "else" section.
It will be correct to give a message when you cannot find all the data except do{}while(true).
Like this;
public string ReadCell(int row, int column)
{
column += 1;
do
{
row++;
if(((_Excel.Range)ws.Cells[row, column]).Value2 == null)
break;
_Excel.Range range = (_Excel.Range)ws.Cells[row, column];
if (range.Value.ToString() == "Z_KomSilnice_L (24200)/7")
{
range = (_Excel.Range)ws.Cells[row, column + 1];
return range.Value.ToString();
}
} while (true);
MessageBox.Show("Hodnota nenalezena!");
return "";
}
I am trying to come up with a solution which reads CSV files and edit them from open file dialogue
I'm able to read the file and display it to the data grid view but can only edit or update from the data grid, not with textboxes and button.
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "CSV Files (*.csv)|*.csv";
if (dialog.ShowDialog() == DialogResult.OK)
{
DataTable table = CSVReader.ReadCSVFile(dialog.FileName, true);
dataGridView1.DataSource = table;
}
assist with the syntax for editing CSV files
I had to read this question a few times before I fully understood what you are asking for. As I understand it, you want to do Insert, Update, and Delete operations in a DataGridView, and then write the results to a CSV file, right. You don't want to do the operations directly on the CSV file, right. With that clarified, try the script below and feed back.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
txtFile.Text = openFileDialog1.FileName;
BindData(txtFile.Text);
}
private void BindData(string filePath)
{
DataTable dt = new DataTable();
string[] lines = System.IO.File.ReadAllLines(filePath);
if (lines.Length > 0)
{
//first line to create header
string firstLine = lines[0];
string[] headerLabels = firstLine.Split(',');
foreach (string headerWord in headerLabels)
{
dt.Columns.Add(new DataColumn(headerWord));
}
//For Data
for (int i = 1; i < lines.Length; i++)
{
string[] dataWords = lines[i].Split(',');
DataRow dr = dt.NewRow();
int columnIndex = 0;
foreach (string headerWord in headerLabels)
{
dr[headerWord] = dataWords[columnIndex++];
}
dt.Rows.Add(dr);
}
}
if (dt.Rows.Count > 0)
{
dataGridView1.DataSource = dt;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;
//Add the Header row for CSV file.
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
csv += column.HeaderText + ',';
}
//Add new line.
csv += "\r\n";
//Adding the Rows
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value != null)
{
//Add the Data rows.
csv += cell.Value.ToString().TrimEnd(',').Replace(",", ";") + ',';
}
// break;
}
//Add new line.
csv += "\r\n";
}
//Exporting to CSV.
string folderPath = "C:\\Users\\Excel\\Desktop\\";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
File.WriteAllText(folderPath + "test.csv", csv);
MessageBox.Show("");
}
catch
{
MessageBox.Show("");
}
}
}
}
By clicking on the "Synchronize" button we will collect the stock numbers of the 2 tables and print them on the stock number of the 1st table.
I have two excel files side by side and I'm having trouble updating them
(addition + transfer).
Synchronize
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Excel;
using Microsoft.Office.Core;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataSet ds;
DataSet ds2;
OpenFileDialog of;
OpenFileDialog ofl;
FileStream fs;
FileStream fst;
IExcelDataReader okuyucu;
IExcelDataReader okuyucu1;
DataTable dt;
DataTable dts;
DataRow new_data_row;
int adet;
int adet2;
int StokNo1;
int StokNo2;
private void button3_Click(object sender, EventArgs e)//Synchronize Button
{
int Adet = Int32.Parse(dataGridView1.Columns[2].Index.ToString());
int Adet2 = Int32.Parse(dataGridView2.Columns[2].Index.ToString());
int StokNo1 = Int32.Parse(dataGridView1.Columns[0].Index.ToString());
int StokNo2 = Int32.Parse(dataGridView2.Columns[0].Index.ToString());
foreach (DataTable dt in ds.Tables)
{
for (int i = 0; i < ds.Tables.Count; i++)
{
StokNo1 = Int32.Parse(dataGridView1.Columns[0].Index.ToString());//The StokNo belonging to DataGridWiew1.
Adet = Int32.Parse(dataGridView1.Columns[2].Index.ToString());//The number belonging to DataGridWiew1.
}
}
foreach (DataTable dt2 in ds2.Tables)
{
for (int j = 0; j < ds2.Tables.Count; j++)
{
StokNo2 = Int32.Parse(dataGridView2.Columns[0].Index.ToString());//The StokNo belonging to DataGridWiew2.
Adet2 = Int32.Parse(dataGridView2.Columns[2].Index.ToString());//The number belonging to DataGridWiew2.
}
}
if ((StokNo1 == StokNo2))//StokNo is Equal
{
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
int toplam = adet + adet2;
ds.Tables[0].Rows.Add(toplam);
}
}
else
{
ds.Tables[0].Rows.Add();//If stokno is not equal add to the last listed
}
}
private void button4_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Excel|*.xls";
save.OverwritePrompt = true;
save.CreatePrompt = true;
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter kayıt = new StreamWriter(save.FileName);
kayıt.WriteLine(dataGridView1.ToString());
kayıt.Close();
}
}
}
}
if the stock number is equal to add to list , I want to update the number according to the stock code I want to add it at the end if the stock code is different
Sorry for my English. I'm newbie in c#. I have quuestion. I have file txt with data:
20160101 PL01 000000000000000003 PL02 TO 0000000001 1.720 0000000001 0000000002
Finnaly i want import this data to DataGridView but only columns 1,4,7,8,9 without columns 2,3,5 and 6.
I try on start Import all data but I have error
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.IO.StreamReader file = new System.IO.StreamReader("C:\\Users\\terrazo\\Desktop\\test1.txt");
string[] columnnames = file.ReadLine().Split(' ');
DataTable dt = new DataTable();
foreach (string c in columnnames)
{
dt.Columns.Add(c);
}
string newline;
while ((newline = file.ReadLine()) != null)
{
DataRow dr = dt.NewRow();
string[] values = newline.Split(' ');
for (int i = 0; i < values.Length; i++)
{
dr[i] = values[i];
}
dt.Rows.Add(dr);
}
file.Close();
dataGridView1.DataSource = dt;
}
}
}
Can anyone help me how import data from txt file without several columns??
thx for all answer.
I have gone through your code and also the error you are facing and came to know that your text file while taken in account also have null spaces or multiple blank space and when you are split it on whitespace base it will also have some null values. I have updated your code for the same please try it and in case you face some problem please feel free to ask me.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.IO.StreamReader file = new System.IO.StreamReader("C:\\Users\\terrazo\\Desktop\\test1.txt");
string[] columnnames = file.ReadLine().Split(' ');
DataTable dt = new DataTable();
foreach (string c in columnnames)
{
if (c != "")
{
dt.Columns.Add(c);
}
}
string newline;
while ((newline = file.ReadLine()) != null)
{
DataRow dr = dt.NewRow();
string[] values = newline.Split(' ');
for (int i = 0; i < values.Length; i++)
{
if (values[i] != "")
{
dr[i] = values[i];
}
}
dt.Rows.Add(dr);
}
file.Close();
dataGridView1.DataSource = dt;
}
}
}
I am trying to upload .csv file to SQL database, as per my code below when I am trying to read .csv file by assigning the File PATH to a variable my program runs fine, but when I am retrieving the same PATH from File Upload control I am getting File Not Found Exception.
Can anyone please guide me how to get ride off this error. Thanks in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Microsoft.VisualBasic.FileIO;
using System.IO;
public partial class Exercise1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fupPath.HasFile)
{
string csv_file_path = #"C:\TechnicalTest\GskTest\Csv\SampleData.csv";
//string csv_file_path = Path.Combine(Server.MapPath("~/File"), fupPath.FileName);
DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
Response.Write("Rows count:" + csvData.Rows.Count);
}
}
private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
}
return csvData;
}
//protected void btnSubmit_Click(object sender, EventArgs e)
//{
// if(fupPath.HasFile)
// {
// //string csv_file_path = #"C:\TechnicalTest\GskTest\Csv\SampleData.csv";
// String csv_file_path = Path.Combine(Server.MapPath("~/File"), fupPath.FileName);
// fupPath.SaveAs(csv_file_path);
// //string path = Server.MapPath("~/")
// //String csv_file_path = Server.MapPath(fupPath.FileName).ToString();
// //csv_file_path = csv_file_path.Replace(#"\\","\"");
// DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
// Response.Write("Rows count:" + csvData.Rows.Count);
// }
//}
}
you need to save the file first
if (fupPath.HasFile)
{
string filename = Path.GetFileName(fupPath.FileName);
String csv_file_path = Path.Combine(Server.MapPath("~/File"), filename);
fupPath.SaveAs(csv_file_path);
and then read it
DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
In your commented Code Path.Combine(Server.MapPath("~/File"), fupPath.FileName); will not work because fupPath.FileName contains the Full path.
If you want to read a file which is present in your local system.You need to save the file first in required location and then you have to read that file by using that location .
Solution:fupPath.SaveAs(csv_file_path);
i.e;
if (fupPath.HasFile)
{
string csv_file_path = Path.Combine(Server.MapPath("~/File"),fupPath.FileName);
fupPath.SaveAs(csv_file_path);
DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
Response.Write("Rows count:" + csvData.Rows.Count);
}
*Reason:*In order to read file,first we have to know the location of the file.file upload control doesn't give file location(Because of security problems).By using file upload control we can save file in our required location.Then by using that location we can read file.If you don't want to save file.After reading file you can delete that file.