I have an application which uses open file dialog to open an excel file and then convert it to .txt and it works fine, almost. Currently it can only read tables with only numbers in them but I need to add a function so that it could also read letters. What should I change to make it able to read letters/words as well as numbers?
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
}
private void BtnFileOpen_Click(object sender, RoutedEventArgs e)
{
var fileDialog = new System.Windows.Forms.OpenFileDialog();
var result = fileDialog.ShowDialog();
switch (result)
{
case System.Windows.Forms.DialogResult.OK:
var file = fileDialog.FileName;
TxtFile.Text = file;
TxtFile.ToolTip = file;
break;
case System.Windows.Forms.DialogResult.Cancel:
default:
TxtFile.Text = null;
TxtFile.ToolTip = null;
break;
}
}
public void convert_Click(object sender, RoutedEventArgs e)
{
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
exportExcelToTxt(TxtFile.Text, filename);
}
}
static void exportExcelToTxt(string excelFilePath, string outputTxtPath)
{
Dictionary<string, List<long>> values = new Dictionary<string, List<long>>();
using (OleDbConnection excelConnection = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 XML;HDR=YES\"", excelFilePath)))
{
excelConnection.Open();
string firstSheet = getFirstSheetName(excelConnection);
using (OleDbCommand cmd = excelConnection.CreateCommand())
{
cmd.CommandText = string.Format("SELECT * FROM [{0}]", firstSheet);
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt); // Getting all the data in the sheet
foreach (DataRow item in dt.Rows)
{
List<long> toAdd = new List<long>();
string key = item[0] as string;
for (int i = 1; i < dt.Columns.Count; i++)
{
toAdd.Add(Convert.ToInt64(item[i]));
}
values.Add(key, toAdd); // Associating all the "numbers" to the "Name"
}
}
}
}
}
StringBuilder toWriteToTxt = new StringBuilder();
foreach (KeyValuePair<string, List<long>> item in values)
{
// Formatting the output
toWriteToTxt.Append(string.Format("{0}:", item.Key));
foreach (long val in item.Value.Distinct())
{
toWriteToTxt.AppendFormat("\t{0} * {1}\r\n", item.Value.Where(f => f == val).Count(), // Amount of occurrencies of each number
val);
}
}
// Writing the TXT
using (FileStream fs = new FileStream(outputTxtPath, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(toWriteToTxt.ToString());
}
}
}
static string getFirstSheetName(OleDbConnection excelConnection)
{
using (DataTable ExcelTables = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" }))
{
return ExcelTables.Rows[0]["TABLE_NAME"].ToString();
}
}
}
}
You should not convert the values to long in this line:
toAdd.Add(Convert.ToInt64(item[i]));
Also replace all List<long> with List<string>, this should cover pretty much the issue.
Related
I'm trying to import an excel file to SQL server via visual Studio. How do I make it read the data starting from the second row and not the first row of the excel file? My code works perfectly as it is, but I want it to start reading the data from the 2nd row. Here is my 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;
using System.IO;
using ExcelDataReader;
namespace ImportDB2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ope = new OpenFileDialog();
ope.Filter = "Excel Files|*.xls; *.xlsx; *.xlsm";
if (ope.ShowDialog() == DialogResult.Cancel)
return;
FileStream stream = new FileStream(ope.FileName, FileMode.Open);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
DataClasses1DataContext conn = new DataClasses1DataContext();
foreach (DataTable table in result.Tables)
{
foreach (DataRow dr in table.Rows)
{
Employee addtable = new Employee()
{
Serial = Convert.ToInt32(dr[0]),
Name = Convert.ToString(dr[1]),
Class = Convert.ToString(dr[2]),
Department = Convert.ToString(dr[3]),
Status = Convert.ToString(dr[4]),
Position = Convert.ToString(dr[5]),
Email = Convert.ToString(dr[6])
};
conn.Employees.InsertOnSubmit(addtable);
}
}
conn.SubmitChanges();
excelReader.Close();
stream.Close();
MessageBox.Show("YEEESSSS FINALLY");
}
}
}
What line of code should I put for it to start reading on the second row, and where inside my code should I put it in? Hope someone can help, thank you. ^_^
bool skip = true;
foreach (DataRow dr in table.Rows)
{
if(skip)
{
skip = false;
continue;
}
If you just want to skip a row in your for loop for each table, do this:
foreach (DataTable table in result.Tables)
{
bool skippedRow = false;
foreach (DataRow dr in table.Rows)
{
if (!skippedRow)
{
skippedRow = true;
continue;
}
Employee addtable = new Employee()
{
Serial = Convert.ToInt32(dr[0]),
Name = Convert.ToString(dr[1]),
Class = Convert.ToString(dr[2]),
Department = Convert.ToString(dr[3]),
Status = Convert.ToString(dr[4]),
Position = Convert.ToString(dr[5]),
Email = Convert.ToString(dr[6])
};
conn.Employees.InsertOnSubmit(addtable);
}
}
I am trying to make a PDF form filling program. The program should get 2 id's from the PHP script, search the MySQL database, and fill the forms with info based of those two id's, but i cant make the PHP script pass arguments to the c# executable. Maybe u can help me out :)
PHP script :
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("documente", $con);
$idfirma;
$idagent;
$sql="SELECT * FROM `agenti` WHERE `Nume Agent` = '$_GET[numea]'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo "Date agent"."<br>";
echo $row['Nume Agent'];echo " | ";echo $row['Sigiliu'];echo " | ";echo $row['Legitimatie']."<br>"."<br>"."<br>"."<br>"."<br>";
$idagent=$row['ID'];
}
$sql1="SELECT * FROM `dateclienti` WHERE `Cod Fiscal` = '$_GET[codf]'";
$result = mysql_query($sql1);
while($row = mysql_fetch_array($result)) {
echo "Date Firma"."<br>";
echo $row['Nume Societate'];echo " | ";echo $row['Adresa Sediu'];echo " | ";echo $row['Cod Fiscal']."<br>";
$idfirma=$row['ID'];
}
exec("pdfgen\PdfGenerator\bin\Debug\PdfGenerator.exe $idfirma, $idagent 2>&1");
echo $idfirma."<br>"."<br>";
echo $idagent;
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con)
?>
c# scipt :
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using System.IO;
using MySql.Data.MySqlClient;
namespace PdfGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FillForm();
ListFieldNames();
}
/// <summary>
/// List all of the form fields into a textbox. The
/// form fields identified can be used to map each of the
/// fields in a PDF.
/// </summary>
private void ListFieldNames()
{
string pdfTemplate = #"C:\xampp\htdocs\site\pdfgen\PdfGenerator\form.pdf";
// title the form
this.Text += " - " + pdfTemplate;
// create a new PDF reader based on the PDF template document
PdfReader pdfReader = new PdfReader(pdfTemplate);
// create and populate a string builder with each of the
// field names available in the subject PDF
StringBuilder sb = new StringBuilder();
foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)
{
sb.Append(de.Key.ToString() + Environment.NewLine);
}
// Write the string builder's content to the form's textbox
textBox1.Text = sb.ToString();
textBox1.SelectionStart = 0;
}
private void FillForm()
{
string idagent1 = null;
string idfirma1 = null;
string[] args = System.Environment.GetCommandLineArgs();
if(args.Length !=0)
{
idfirma1 = args[1];
idagent1 = args[2];
}
using (var connection = new MySqlConnection("server = localhost; User Id = root; password = ; database = documente;"))
{
connection.Open();
string agenti = "SELECT `Nume Agent` FROM `agenti` WHERE `ID` = #id";
string name1 = null;
using (var cmd = new MySqlCommand(agenti, connection))
{
cmd.Parameters.AddWithValue("#id", idagent1);
MySqlDataReader rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow row in dt.Rows)
{
string name = row["Nume Agent"].ToString();
name1 = name;
}
string pdfTemplate = #"C:\xampp\htdocs\site\pdfgen\PdfGenerator\form.pdf";
string newFile = #"C:\xampp\htdocs\site\pdfgen\PdfGenerator\completed_form.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(
newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
// set form pdfFormFields
// The first worksheet and W-4 form
pdfFormFields.SetField("topmostSubform[0].Page1[0].regcomert[0]", name1);
// flatten the form to remove editting options, set it to false
// to leave the form open to subsequent manual edits
pdfStamper.FormFlattening = true;
// close the pdf
pdfStamper.Close();
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace PdfGenerator
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
I recently asked about a piece of code to hold data for my trading cards. I have a file that contains the overall list of the cards in a CSV file. I was wondering if there was any way to remove a row from the CSV file when the card number is selected and the submit button pressed. The code I currently have is:
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;
using System.IO;
namespace YuGiOh_Card_List
{
public partial class frmAddLOB : Form
{
List<string> cardNo = new List<string>();
List<string> cardName = new List<string>();
List<string> cardRarity = new List<string>();
List<string> cardType = new List<string>();
public frmAddLOB()
{
InitializeComponent();
StreamReader reader = File.OpenText("..\\Debug\\lobList.csv");
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
cardNo.Add(values[0]);
cardName.Add(values[1]);
cardRarity.Add(values[2]);
cardType.Add(values[3]);
cboCardNo.Items.Add(values[0]);
}
reader.Close();
}
private void cboCardNo_SelectedIndexChanged(object sender, EventArgs e)
{
lblCardNoFinal.Text = cardNo[cboCardNo.SelectedIndex];
lblCardNameFinal.Text = cardName[cboCardNo.SelectedIndex];
lblCardRarityFinal.Text = cardRarity[cboCardNo.SelectedIndex];
lblCardTypeFinal.Text = cardType[cboCardNo.SelectedIndex];
}
private void btnAdd_Click(object sender, EventArgs e)
{
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text);
Global.card.Add(card);
File.AppendAllLines(file, new[] { card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter + card.CardType });
MessageBox.Show("Card Added");
}
}
}
So I want the row to be removed from the 'loblist.csv' and added to the LOB file (which it is currently doing). Thanks
This should work (untested). Unfortunately, there's no classes/methods available in .Net (AFAIK) for in-place editing of text files (it makes sense when you think about it I guess). Disclaimer - there are much cleaner ways to do what you're aiming for here functionality-wise, including the approach described by Plutonix above:
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;
using System.IO;
namespace YuGiOh_Card_List
{
public partial class frmAddLOB : Form
{
List<string> cardNo = new List<string>();
List<string> cardName = new List<string>();
List<string> cardRarity = new List<string>();
List<string> cardType = new List<string>();
List<string> Lines = new List<string>();
public frmAddLOB()
{
InitializeComponent();
StreamReader reader = File.OpenText("..\\Debug\\lobList.csv");
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
Lines.Add(line);
cardNo.Add(values[0]);
cardName.Add(values[1]);
cardRarity.Add(values[2]);
cardType.Add(values[3]);
cboCardNo.Items.Add(values[0]);
}
reader.Close();
}
private void cboCardNo_SelectedIndexChanged(object sender, EventArgs e)
{
lblCardNoFinal.Text = cardNo[cboCardNo.SelectedIndex];
lblCardNameFinal.Text = cardName[cboCardNo.SelectedIndex];
lblCardRarityFinal.Text = cardRarity[cboCardNo.SelectedIndex];
lblCardTypeFinal.Text = cardType[cboCardNo.SelectedIndex];
}
private void btnAdd_Click(object sender, EventArgs e)
{
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text,
lblCardTypeFinal.Text);
Global.card.Add(card);
var newLine = card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter +
card.CardType;
File.AppendAllLines(file,
new string [] {newLine});
if (Lines.Contains(newLine))
{
Lines.Remove(newLine);
File.WriteAllLines("..\\Debug\\lobList.csv", Lines);
}
MessageBox.Show("Card Added");
}
}
}
this is my code and I also have a snippet in the link below of what my program looks like when run. My problem is with the second text box and that it is filling out with random gibberish. My first text box is working perfectly it is picking a random first name from my text file and putting it into the text box. I dont understand what my second text file isnt doing the same'?
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;
using System.IO;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
{
Random r = new Random();
int currentLinefirst = 1;
string pick = null;
foreach (string line in File.ReadLines("C:\\Users\\Admin\\Desktop\\C# Programs\\WindowsFormsApplication5\\WindowsFormsApplication5\\First Names.txt"))
{
if (r.Next(currentLinefirst) == 0)
{
pick = line;
}
++currentLinefirst;
}
textBox1.Text = pick;
}
Random n = new Random();
int currentLinelast = 1;
string pick2 = null;
foreach (string line1 in File.ReadLines("C:\\Users\\Admin\\Desktop\\C# Programs\\WindowsFormsApplication5\\WindowsFormsApplication5\\Last Names.txt"))
{
if (n.Next(currentLinelast) == 0)
{
pick2 = line1;
}
++currentLinelast;
}
textBox2.Text = pick2;
}
}
}
i am getting this output of random numbers in textbox
It is probably because your second file contains a line with multiple names. When you call File.ReadLines, it will return an array of string on each line
Try separating you last names with line feeds.
To save the text to a text file use
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\Admin\Desktop\test.txt", true))
{
file.WriteLine("First Name: {0} Last Name: {1}", textBox1.Text, textBox2.Text);
}
{0} and {1} are placeholders
if the file is does not exist it will create a new file to the given path and if the file already exists then it will add new entry to the file.
You can try this:
string firstname = textBox1.Text;
string lastname = textBox2.Text;
Byte[] info = new UTF8Encoding(true).GetBytes(firstname + lastname);
string FilePath = yourpath + DateTime.Now.ToString("dd-MMM-yyyy") + ".txt";
using (FileStream fs = File.Create(FilePath))
{fs.Write(info, 0, info.Length);}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.IO;
using System.Xml.XmlConfiguration;
using OATAssetTracking.Solution.Presenter;
namespace WindowsFormsApplication2
{
public class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
string path = "SearchDefinition.xml";
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(null, #"D:\searchDefinition.xsd");
Exception firstException = null;
var settings = new XmlReaderSettings
{
Schemas = schemas,
ValidationType = ValidationType.Schema,
ValidationFlags =
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ReportValidationWarnings
};
settings.ValidationEventHandler +=
delegate(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
Console.WriteLine(args.Message);
}
else
{
if (firstException == null)
{
firstException = args.Exception;
}
Console.WriteLine(args.Exception.ToString());
}
};
Search result=null;
using (var input = new StreamReader(path))
{
using (XmlReader reader = XmlReader.Create(input, settings))
{
XmlSerializer ser = new XmlSerializer(typeof(Search));
result = (Search)ser.Deserialize(reader);
}
}
if (firstException != null)
{
throw firstException;
}
MessageBox.Show("Deserialization Done!!!!");
}
}
}
In this one,
Here Search is class name which is generated from XSD
result = (Search)ser.Deserialize(reader);
This above statement works fine in Windows forms Application, but fails to work with Windows Device Project " No errors but just hangs there not executing".
Actually, The problem in the above code was
result = (Search)ser.Deserialize(reader);
XML reader which has been created cannot be used while directly de-serializing it to an object. This kind of above code is supported only in the "Windows Forms Application" in VS2008 and its not getting supported in any kind of "Smart Device Projects".
So, Reader settings can be included and XML errors can be handled by any handlers like ValidationEventHandler.
So, Below code validates the XML against XSD and also de-serializes to the object initialized.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.IO;
using OATAssetTracking.Solution.Presenter;
namespace WindowsFormsApplication2
{
public class Program
{
static void Main()
{
string path2 = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\" + "SearchDefinition.xsd";
string path1 = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\" + "SearchDefinition.xml";
XmlSchema schema;
using (var schemaReader = XmlReader.Create(path2))
{
schema = XmlSchema.Read(schemaReader, ValidationEventHandler);
}
var schemas = new XmlSchemaSet();
schemas.Add(schema);
var settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = schemas;
settings.ValidationFlags =
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += ValidationEventHandler;
using (var validationReader = XmlReader.Create(path1, settings))
{
while (validationReader.Read())
{
}
}
MessageBox.Show("XML verified Successfully....");
XmlSerializer ser = new XmlSerializer(typeof(Search));
Search result = ser.Deserialize(new FileStream(path1, FileMode.Open)) as Search;
MessageBox.Show("Deserilization Done Successfully!!!!");
}
private static void ValidationEventHandler(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Error)
{
throw args.Exception;
}
}
}
}