how to insert data from csv file into database using asp.net - asp.net

I am trying to insert data that is saved in csv format.i tried the below code but the problem is when i run the code it only save data from the second line.can anyone correct my code so that i can save my data from the first line.
CODE:-
protected void Page_Load(object sender, EventArgs e)
{
csvInsert();
}
public void csvInsert()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectme"].ConnectionString);
conn.Open();
//DataTable dt = new DataTable("insert");
string filename = "C:\\Users\\Aowi\\Desktop\\asdf.csv";
SqlTransaction transaction = conn.BeginTransaction();
try
{
using (StreamReader file = new StreamReader(filename))
{
CsvReader csv = new CsvReader(file, true, '\t');
SqlBulkCopy copy = new SqlBulkCopy(conn, SqlBulkCopyOptions.KeepIdentity, transaction);
copy.DestinationTableName = "[Live]";
copy.WriteToServer(csv);
transaction.Commit();
}
}
catch (Exception ex)
{
transaction.Rollback();
}
finally
{
conn.Close();
}
}
Saved in Database as:-
csv file is:-
1,Germany,? - ?,Portugal
2,half-time,(? - ?),
3
4,Milorad Mazic (Serbia),
5,Iran,? - ?,Nigeria
6,half-time,(? - ?),
7
8,Carlos Vera (Ecuador),
9,Ghana,? - ?,USA
10,half-time,(? - ?),
Desired output is insert each and every data from the csv file to each cell in database.

It looks like the CSV reader expects a header row. Try adding a header to the top and see if that resolves. Try passing FALSE to the CSVReader, as well. It looks like that flag might be used to signify if you have a header row or not.

Related

An error has occurred during report (rdlc) processing

I got the error While I am creating RDLC report.
Error is that
" An error has occurred during report processing.
Cannot create a connection to data source 'ds_SalesQuotation'.
Calling 'Read' when the data reader is closed is not a valid operation.
Invalid attempt to call Read when reader is closed. "
I create ds_SalesQuotation.xsd file.
In rdlc report give dataset name as 'dsSalesQuotation' and set datasourse as 'ds_SalesQuotation'
my code is on reportviewr(.aspx)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (BillingAppEntities context = new BillingAppEntities())
{
var val = context.Sp_SalesQuotation(id);
ReportDataSource rd = new ReportDataSource("dsSalesQuotation", val);
ReportViewer1.LocalReport.DataSources.Add(rd);
ReportViewer1.LocalReport.Refresh();
}
}
}
Is there any mistaken in my code.please check it anybody..
I got my error.I re-write the above code,that is given below.
Now it is working
private void PopulateReport(int id)
{
List<Sp_SalesQuotation_Result> ls = new List<Sp_SalesQuotation_Result>();
using (BillingAppEntities context = new BillingAppEntities())
{
ls = context.Sp_SalesQuotation(id).ToList();
}
ReportDataSource rd = new ReportDataSource("dsSalesQuotation", ls);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rd);
ReportViewer1.LocalReport.Refresh();
}

Reading the Excel sheeet from Asp.net?

Getting error while reading the excel sheet from the local drive. I am using asp.net to read the excel sheet. My error:
The Microsoft Office Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data.
protected void btnup_Click(object sender, EventArgs e)
{
string Extension = Path.GetExtension("Book1.xlsx");
string FolderPath = #"D:/Book1.xlsx";
Import_To_Grid(FolderPath, Extension);
}
private void Import_To_Grid(string FilePath, string Extension )
{
string conStr = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"] .ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"] .ConnectionString;
break;
}
using (OleDbConnection conn = new OleDbConnection(conStr))
{
conn.Open();
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
string firstSheetName = sheetsName.Rows[0][2].ToString();
string sql = string.Format("SELECT * FROM [{0}]", firstSheetName);
OleDbDataAdapter ada = new OleDbDataAdapter(sql, conStr);
DataSet set = new DataSet();
ada.Fill(set);
}
}
I am getting error at conn.Open().
This error may happen because you are opening that excel file by using MS Office or another process is opening your excel file.
i got the solution for my question. Actually i did some thing wrong in connection string in connection string at source i not given the path, that is the reason it is throwing error.

Insert CSV from file upload control directly to memory stream without physical path

I am not sure if this is possible so it would be nice to have some help.
What I want to do is use a fileupload control in asp.net to select a csv file. Then use my submit button on the page to run my server side code which will take that csv file and put it into memory stream where it will be parsed and then added to collection object.
I do know it's easier to save the csv file to a physical path and then do some kind of cleanup where I delete the file but if possible I would like to do it this way.
See below for code so far:
protected void btnUpload_Click(object sender, EventArgs e)
{
string connectingString = "";
if (ctrlFileUpload.HasFile)
{
string fileName =
Path.GetFileName(ctrlFileUpload.PostedFile.FileName);
string fileExtension =
Path.GetExtension(ctrlFileUpload.PostedFile.FileName);
ReadCsv(fileName);
}
}
protected void ReadCsv(string fileName)
{
// Some logic for parsing csv file in memory stream
}
}
Any ideas? Thanks!
I know this is an old question, but the below code will work for reading your posted text file into a memory stream using a StreamReader and is compatible with .NET 4.0:
protected void ReadCsv()
{
StreamReader reader = new StreamReader(ctrlFileUpload.PostedFile.InputStream);
string content = reader.ReadToEnd();
}
Note, this method is only efficient if you have enough memory on the server to handle larger files for multiple users concurrently. You don't want to use this approach if you have hundreds of users posting files simultaneously to a memory stream and causing your server to crash due to insufficient available memory. You'll also want to check if this is an acceptable method if you're on a shared hosting environment.
Does this help?
This should give you the stream. So you'd make your ReadCsv method accept a reference to the stream, and pass that to it rather than the filename, and work against the stream.
MSDN FileUpload.FileContent Property
//Try below one to capture data in MemoryStream from FileUpload Control
protected void btnFileUpload_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
#region Capture file data in Memory Stream
byte[] fileData = null;
Stream fileStream = null;
int length = 0;
length = FileUploadControl.PostedFile.ContentLength;
fileData = new byte[length + 1];
fileStream = FileUploadControl.PostedFile.InputStream;
fileStream.Read(fileData, 0, length);
//Use MemoryStream to capture file data
MemoryStream stream = new MemoryStream(fileData);
Session["FileUploaded"] = stream;
#endregion
StreamReader strFile;
using (strFile = new StreamReader(stream))
{
string line;
DataTable dtStudentData = CreateDataTable();
DataRow drStudentRow;
List<String> errorMessages = new List<String>();
// Read and display lines from the file until the end of the file is reached.
while ((line = strFile.ReadLine()) != null)
{
if (line.Trim().Length > 0)
{
System.Threading.Thread.Sleep(1000);
string[] columns = line.Split('\t'); //splitting the line which was read by the stream reader object
Int32 charpos = (Int32)strFile.GetType().InvokeMember("charPos", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, strFile, null);
Int32 charlen = (Int32)strFile.GetType().InvokeMember("charLen",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetField
, null, strFile, null);
int lineno = (Int32)strFile.BaseStream.Position - charlen + charpos;
//Add data row in Data Table
drStudentRow = dtStudentData.NewRow();
// TO DO code - Fill data table
dtStudentData.Rows.Add(drStudentRow);
}
}
strFile.Dispose();
dtStudentData.Rows.RemoveAt(0); //Remove the first column since its the column name not necessary to insert in the database table
PopulateStudentInvalidDataGridView(dtStudentData); // Bind Grid
Session["StudentData_FileParsedStudentRegistrtaionTable"] = dtStudentData;
strFile.Close(); //release the stream reader
}
}
catch (Exception ex)
{
String error = ex.Message;
}
}
}

Download multiple excel files from the DataTable

I am trying to execute a query using for loop. For each loop it should download an excel file. The solution works perfectly, but only the first file is downloaded and the other two files are not downloaded. I have also attached the complete code below.
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Btn_Click(object sender, EventArgs e)
{
DataTable it = GetList();
foreach(DataRow dr in it.Rows)
{
string a = dr[0].ToString();
for (int i = 0; i < 3; i++)
{
string inm = it.Rows[i][0].ToString();
DataTable gt = GetData(inm);
ExportToSpreadsheet(gt, "Samples");
}
}
}
public DataTable GetData(string i)
{
SqlCommand command = null;
SqlConnection conn = null;
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
command = new SqlCommand("SELECT id, name, class FROM StudentTable WHERE (id = " + i + ") ORDER BY name";
DataTable dt = new DataTable();
SqlDataAdapter ada = new SqlDataAdapter(command);
ada.Fill(dt);
return dt;
}
public static void ExportToSpreadsheet(DataTable table, string name)
{
HttpContext context = HttpContext.Current;
context.Response.ClearContent();
context.Response.ContentType = "text/vnd.ms-excel";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".xls");
string tab = "";
foreach (DataColumn dc in table.Columns)
{
context.Response.Write(tab + dc.ColumnName);
tab = "\t";
}
context.Response.Write("\n");
context.Response.Write("\n");
int i;
foreach (DataRow dr in table.Rows)
{
tab = "";
for (i = 0; i < table.Columns.Count; i++)
{
context.Response.Write(tab + dr[i].ToString());
tab = "\t";
}
context.Response.Write("\n");
}
context.Response.End();
}
I have seen posts similar to this. Some people have recommended that, zip files can be created on the server and download multiple excel files in "zip" folder. If it is possible, how can I implement it to the above solution?
You're calling response.end after creating the first file - which aborts the rest of the process.
I don't think you'll be able to create 3 excel files for download using this method.
As an alternative you could create 3 CSV files on disk, then use a zip library to zip them up.
see zipping files
Or you could use JET with an Excel connection string and use SQL Insert statements to push your data into an empty excel file. And use a different worksheet for each of your tables
write to excel with JET (but this limits you to 32bit)
Or you could use a third part control to write an excel file with the three tables as worksheets
Infragistics excel control
But if I were you - I'd just present the user with 3 different links they could click on.

Inserting an image into MySQL database using file upload control

I would like to insert the image into a MySQL database using the file upload control in Visual Studio. I am using ASP.NET 3.5 and MySQL Community Server with ODBCc and .NET Connectors.
Here some code that will pull the posted file into a byte array. It'll then pass it down to MySQL. Assumes a varbinary column data type. Modify as you need.
if(FileUploadControl.HasFile)
{
try
{
byte[] img = new byte[FileUploadControl.PostedFile.ContentLength- 1];
img = FileUploadControl.FileBytes;
InsertImg(img);
}
catch(Exception ex)
{
}
}
....
public void InsertImg(byte[] img) //untested code
{
using (MySqlConnection conn = new MySqlConnection(connString))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = #"INSERT INTO MyTable(MyImage) VALUES (#Img)";
cmd.Parameters.Add("#Img", System.Data.SqlDbType.VarBinary); //or SqlDbType.Image
cmd.Parameters["#Img"].Value = img;
conn.Open();
cmd.ExecuteNonQuery();
}
}
}

Resources