Code query database:
I can't save the PDF files to my database, I have a serious problem in the database storage area.
public void ADDWORK(String MAW, string NAMEW, string IDUSER, bool Image,string room, byte[] document,string content,bool donework)
{
String strSql = string.Format("INSERT INTO WORK(IDWORD,NAMEWORk,IDUSER,IMAGES,IDROOM,DOCUMENTS,CONTENT,DONEWORK)VALUES('{0}',N'{1}',N'{2}','{3}',N'{4}',N'{5}',N'{6}',N'{7}')"
, MAW, NAMEW, IDUSER, Image,room,document,content,donework);
db.ExecuteNonQuery(strSql);
}
Code call function:
byte[] pdf;
public void UploadFlie(string file)
{
FileStream fileStream = File.OpenRead(file);
byte[] contents = new byte[fileStream.Length];
fileStream.Read(contents, 0, (int)fileStream.Length);
fileStream.Close();
pdf = contents;
}
private void button1_Click(object sender, EventArgs e)
{
UploadFlie(filename);
dg.ADDWORK(idword, textBox1.Text,"1", false,"ROOM1", pdf, richTextBox1.Text, false);
MessageBox.Show("Done!");
}
here is my example how to get any file and save it on database.
I use two diffrent methods
Saving byte array.
Saving Stream
First you need to create column varbinary(MAX) in my case I called it - PdfFile
and PdfExtn column to save the type of the file As varchar(10) (You can use 4).
Saving byte array:
private void btnGetFile_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
string extn = new FileInfo(file).Extension;
try
{
byte[] fileBytes = File.ReadAllBytes(file);
string cmd = "INSERT INTO Employee(Id,FirstName,LastName,Email,Password,PdfFile,FileExtn) VALUES (#Id,#FirstName,#LastName,#Email,#Password,#PdfFile,#FileExtn)";
List<SqlParameter> l = new List<SqlParameter>();
l.Add(new SqlParameter("#Id", "101"));
l.Add(new SqlParameter("#FirstName", "Aviv"));
l.Add(new SqlParameter("#LastName", "Halevy"));
l.Add(new SqlParameter("#Email", "Assadsa#gmail.com"));
l.Add(new SqlParameter("#Password", "123456"));
SqlParameter sp = new SqlParameter("#PdfFile", SqlDbType.VarBinary, -1);
sp.Value = fileBytes;
l.Add(sp);
l.Add(new SqlParameter("#FileExtn", extn));
if (DAL.Database.ParametersCommand(cmd, l) > 0)
textBox1.Text = "SUCCESS! Save with byte array";
}
catch (IOException ex)
{
}
}
}
Write the file from bytes:
private void btnReadFromDb_Click(object sender, EventArgs e)
{
string cmd = "SELECT * FROM Employee WHERE Id = '101'";
string path = "YOUR_PATH\\Test";
DataTable dt = DAL.Database.GetDataTable(cmd);
if (dt != null && dt.Rows.Count > 0)
{
Byte[] file = (Byte[])dt.Rows[0]["PdfFile"];
string extn = dt.Rows[0]["FileExtn"].ToString();
path = Path.Combine(path, "Test321"+extn);
File.WriteAllBytes(path, file);
Process.Start(path);
}
}
And the result:
Using Stream
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
using (Stream stream = File.OpenRead(file))
{
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
string extn = new FileInfo(file).Extension;
string cmd = "INSERT INTO Employee(Id,FirstName,LastName,Email,Password,PdfFile,FileExtn) VALUES (#Id,#FirstName,#LastName,#Email,#Password,#PdfFile,#FileExtn)";
List<SqlParameter> l = new List<SqlParameter>();
l.Add(new SqlParameter("#Id", "102"));
l.Add(new SqlParameter("#FirstName", "Aviv"));
l.Add(new SqlParameter("#LastName", "Halevy"));
l.Add(new SqlParameter("#Email", "Assadsa#gmail.com"));
l.Add(new SqlParameter("#Password", "123456"));
l.Add(new SqlParameter("#PdfFile", buffer));
l.Add(new SqlParameter("#FileExtn", extn));
if (DAL.Database.ParametersCommand(cmd, l) > 0)
textBox1.Text = "SUCCESS! Save with Stream";
}
}
}
Write the file from stream:
private void button2_Click(object sender, EventArgs e)
{
string cmd = "SELECT * FROM Employee WHERE ID = '102'";
string path = "YOUR_PATH\\Test";
DataTable dt = DAL.Database.GetDataTable(cmd);
if (dt != null && dt.Rows.Count > 0)
{
Byte[] file = (Byte[])dt.Rows[0]["PdfFile"];
string extn = dt.Rows[0]["FileExtn"].ToString();
path = Path.Combine(path, "Test123"+extn);
File.WriteAllBytes(path, file);
Process.Start(path);
}
}
And the result:
Note:
In my examples the DAL project has a static methods that runs my sql commands.
I'm starting to play with C# / .NET. My work background is Python.
Im having difficulty solving the conversion from Excel to TXT.
What i need the txt file to look like is:
ROW1COLUM1;ROW1COLUM2;ROW1COLUM3 //Note the lack of ";" on line break.
ROW2COLUM1;ROW2COLUM2;ROW3COLUM3
I am trying to at least save 1 cell in the txt but i cant. Code below:
private void button1_Click(object sender, EventArgs e) // Go
{
File.Create(#"C: \Users\AG\.PyCharmCE2017.2\config\scratches\testnet.txt").Close();
TextWriter tw = new StreamWriter(#"C: \Users\AG\.PyCharmCE2017.2\config\scratches\testnet.txt");
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fileName);
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
string[] dataRow = new string[15]; //fixed number for now
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
dataRow[j - 1] = xlWorksheet.Cells[i, j].Value.ToString();
}
tw.WriteLine(dataRow[1]); // Just checking if i can write something
}
MessageBox.Show("OK");
tw.Close();
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
I also need to save the .txt file as unicode, in case that matters.
This is probably very basic, i just couldn't find an answer.
Thanks
EDIT:
I managed to make it work. I also added a backgroundWorker.
The problem i have is performance. Can someone point me in the right direction?
Code:
if (goNoGo)
{
string sourceDirectory = Path.GetDirectoryName(fileName);
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
File.Create(sourceDirectory + filenameWithoutExtension).Close();
TextWriter tw = new StreamWriter(sourceDirectory + "\\" + filenameWithoutExtension + ".txt", true, Encoding.Unicode);
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fileName);
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
string dataRow = "";
int z = 1;
if (checkBox1.Checked)
{
z = 2;
}
int cont = 0;
for (float i = z; i <= rowCount; i++)
{
if (i % 250 == 0) // every 250 rows, check BW updates
{
cont = ((int)((i / rowCount) * 100));
backgroundWorker1.ReportProgress(cont);
//MessageBox.Show(cont.ToString());
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
for (int j = 1; j <= colCount; j++)
{
try
{
if (j == 1)
{
dataRow = xlWorksheet.Cells[i, j].Value.ToString();
}
else
{
dataRow += ";";
dataRow += xlWorksheet.Cells[i, j].Value.ToString();
}
}
catch (Exception ex) // catches empty cells
{
if (j == 1)
{
dataRpw = "";
}
else
{
dataRow += ";";
dataRow += "";
}
continue;
}
}
tw.WriteLine(dataRow);
}
tw.Close();
//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
backgroundWorker1.ReportProgress(100);
}
else if (extensionWrong)
{
MessageBox.Show("File must be .xls");
}
else
{
MessageBox.Show("Load a file");
}
A 30k row file can take up to an hour. Any ideas?
Please try this and feedback.
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;
namespace test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataSet result = new DataSet();
private void button1_Click(object sender, EventArgs e)
{
string fileName = "";
fileName = textBox3.Text;
if (fileName == "")
{
MessageBox.Show("Enter Valid file name");
return;
}
converToCSV(comboBox1.SelectedIndex);
}
private void button2_Click(object sender, EventArgs e)
{
string Chosen_File = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Chosen_File = openFileDialog1.FileName;
}
if (Chosen_File == String.Empty)
{
return;
}
textBox1.Text = Chosen_File;
getExcelData(textBox1.Text);
}
private void button3_Click(object sender, EventArgs e)
{
DialogResult result = this.folderBrowserDialog1.ShowDialog();
string foldername = "";
if (result == DialogResult.OK)
{
foldername = this.folderBrowserDialog1.SelectedPath;
}
textBox2.Text = foldername;
}
private void getExcelData(string file)
{
if (file.EndsWith(".xlsx"))
{
// Reading from a binary Excel file (format; *.xlsx)
FileStream stream = File.Open(file, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
result = excelReader.AsDataSet();
excelReader.Close();
}
if (file.EndsWith(".xls"))
{
// Reading from a binary Excel file ('97-2003 format; *.xls)
FileStream stream = File.Open(file, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
result = excelReader.AsDataSet();
excelReader.Close();
}
List<string> items = new List<string>();
for (int i = 0; i < result.Tables.Count; i++)
items.Add(result.Tables[i].TableName.ToString());
comboBox1.DataSource = items;
}
private void converToCSV(int ind)
{
// sheets in excel file becomes tables in dataset
//result.Tables[0].TableName.ToString(); // to get sheet name (table name)
string a = "";
int row_no = 0;
while (row_no < result.Tables[ind].Rows.Count)
{
for (int i = 0; i < result.Tables[ind].Columns.Count; i++)
{
a += result.Tables[ind].Rows[row_no][i].ToString() + ",";
}
row_no++;
a += "\n";
}
string output = textBox2.Text + "\\" + textBox3.Text + ".csv";
StreamWriter csv = new StreamWriter(#output, false);
csv.Write(a);
csv.Close();
MessageBox.Show("File converted succussfully");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
comboBox1.DataSource = null;
return;
}
}
}
I tried to write code to import an Excel file to a database using C# and ADO.net I finally got the code to run but the output is wrong.
using Excel;
using System.IO;
namespace ExpPerson
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btnImport_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog op = new OpenFileDialog();
op.Filter = "Excel Workbook| *.xls;*.xlsx;*.xlsm";
if (op.ShowDialog() == DialogResult.Cancel)
return;
FileStream stream = new FileStream(op.FileName, FileMode.Open);
IExcelDataReader excelreader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelreader.AsDataSet();
MaamoonKhalidIssueEntities db = new MaamoonKhalidIssueEntities();
foreach (DataTable table in result.Tables)
{
foreach (DataRow dr in table.Rows)
{
Person addtable = new Person()
{
nname = Convert.ToString(dr[0]),
ncode = Convert.ToString(dr[1]),
nTel1 = Convert.ToString(dr[2]),
nTel2 = Convert.ToString(dr[3]),
nFax = Convert.ToString(dr[4]),
nEmail = Convert.ToString(dr[5]),
nAdd = Convert.ToString(dr[6])
};
}
}
db.SaveChanges();
excelreader.Close();
stream.Close();
MessageBox.Show("Import Sucess","Good",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
But there is an issue where the code runs without any errors but the data in the database isn't right and I can't figure out what is wrong.
You need to call db.People.Add(addtable); on each iteration of the DataRow loop.
So:
foreach (DataRow dr in table.Rows)
{
Person addtable = new Person()
{
nname = Convert.ToString(dr[0]),
ncode = Convert.ToString(dr[1]),
nTel1 = Convert.ToString(dr[2]),
nTel2 = Convert.ToString(dr[3]),
nFax = Convert.ToString(dr[4]),
nEmail = Convert.ToString(dr[5]),
nAdd = Convert.ToString(dr[6])
};
db.People.Add(addtable)
}
Otherwise, Entity Framework doesn't know you want them inserted to the database.
I copied these codes from this link and tried it.
however, it did not work for me. Is there anything wrong with my codes or is there any other way? Or should there be anything to be improved on the codes. The codes are below.
When I have selected the range and pressed ok, nothing happens.
Nothing will appear in my datagridview
private Microsoft.Office.Interop.Excel._Application App;
private Microsoft.Office.Interop.Excel.Range rng = null;
private System.Data.DataTable ConvertRangeToDataTable()
{
try
{
System.Data.DataTable dt = new System.Data.DataTable();
int ColCount = rng.Columns.Count;
int RowCount = rng.Rows.Count;
for (int i = 0; i < ColCount; i++)
{
DataColumn dc = new DataColumn();
dt.Columns.Add(dc);
}
for (int i = 1; i <= RowCount; i++)
{
DataRow dr = dt.NewRow();
for (int j = 1; j <= ColCount; j++)
{
dr[j + 1] = rng.Cells[i, j].Value2;
dt.Rows.Add(dr);
}
}
return dt;
}
catch { return null; }
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "Excel Worksheets|*.xls;*.xlsx;*.xlsm;*.csv";
if (OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
App = new Microsoft.Office.Interop.Excel.Application();
App.Visible = true;
App.Workbooks.Open(OFD.FileName);
}
else { return; }
try
{
rng = (Microsoft.Office.Interop.Excel.Range)App.InputBox("Please select a range", "Range Selection");
}
catch { App.Quit(); }; //user pressed cancel on input box
if (rng != null)
{
System.Data.DataTable dt = ConvertRangeToDataTable();
if (dt != null)
{
dataGridView1.DataSource = dt;
}
Dispose();
}
}
private void Dispose()
{
try { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(rng); }
catch { }
finally { rng = null; }
try { App.Quit(); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(App); }
catch { }
finally { App = null; }
}
I have point files like:
I have created code that allows users to select the files from a dialog box and it will populate the data to the gridview.
private void cmdload_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Point");
table.Columns.Add("X");
table.Columns.Add("Y");
table.Columns.Add("Z");
table.Columns.Add("R");
table.Columns.Add("A");
table.Columns.Add("B");
table.Columns.Add("C");
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "C:\\";
openFileDialog1.Filter = "Data Files (*.PNT)|*.PNT";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
string filename = openFileDialog1.FileName;
using (var reader = File.OpenText(filename))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(' ');
table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7]);
}
dataGridView1.DataSource = table;
}
}
}
}
catch (Exception ex) // you need to add the catch block if yo are using try block
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
This code works fine, however the datagridview does not display the value.
If you are not creating the DataGridView columns through code then you have to set the DataPropertyName of the DataGridViewColumn to the columns ids in the DataTable.
Sample code:
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
col1.Name = "Point";
col1.HeaderText = "Point";
col1.DataPropertyName = "Point";
dataGridView1.Columns.Add(col1)
The other way is to set AutoGenerateColumns property to true to create the required columns automatically and bind the data to the DataTable. By this you don't have to create columns through code like in the above sample code.
dataGridView1.AutoGenerateColumns = true;