Reading the Excel sheeet from Asp.net? - 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.

Related

Delete Asp.Net Databse Connection Tutorial. Receiving CS103 error code

I am new to programming and found these great tutorials on the Guru99.com site. Under the insert, update, Delete Asp.Net Database Connection Tutorial I was able to make the connection to the database successfully where the message came back "Connection Made".
The problem I am having is under the ASP.NET Read Database using the SQLDataReader. When I added the code and ran the program, I got a CS103 code which is The name 'sqlquery' does not exist in the current context. I thought that had to rem out the response.write and ccn.close statements thinking that the connection needed to be opened and still got the same error code. I hoping to find someone who are familiar with this tutorial. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
String connetionString; //Variable declaration
SqlConnection cnn;
connetionString = #"Data Source=BMIS-JHanlon3\SQLEXPRESS;Initial Catalog=DemoDB;User ID=sa;Password=demo123"; //Set connection string
cnn = new SqlConnection(connetionString); //Assign connection
cnn.Open(); //open and close the connection
// Response.Write("Connection Made");
// cnn.Close();
SqlCommand command;
SqlDataReader dataReader;
String sql, Output = " ";
sql = "Select TutorialID,TutorialName from DemoDB";
command = new SqlCommand(sql, cnn);
dataReader = sqlquery.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();
}
}
}

Excel File Upload Working Locally But Not On Azure

Using ASP.net MVC on Azure. As subject states, it's working fine locally but not on Azure. The form renders properly. Upon submitting the form, I get my page header and a message stating "An error occurred while processing your request." I've checked the database and all the fields were carried over properly. I'm not sure what else to use to troubleshoot.
namespace WebApplication12.Controllers
{
[Authorize]
public class DashboardController : Controller
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
OleDbConnection Econ;
// GET: Dashboard
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
string filename = Guid.NewGuid() + Path.GetDirectoryName(file.FileName);
string filepath = "/excel/" + filename;
file.SaveAs(Path.Combine(Server.MapPath("/excel/"), filename));
InsertExcelData(filepath, filename);
ViewBag.Message = "File successfully uploaded.";
return View();
}
private void ExcelConn(string filepath)
{
string constr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", filepath);
Econ = new OleDbConnection(constr);
}
private void InsertExcelData(string filepath, string filename)
{
string fullpath = Server.MapPath("/excel/") + filename;
ExcelConn(fullpath);
string query = string.Format("Select * from [{0}]", "Sheet1$");
OleDbCommand Ecom = new OleDbCommand(query, Econ);
Econ.Open();
DataSet ds = new DataSet();
OleDbDataAdapter oda = new OleDbDataAdapter(query, Econ);
Econ.Close();
oda.Fill(ds);
DataTable dt = ds.Tables[0];
dt.Columns.Add(new DataColumn("Email", typeof(System.String)));
dt.Columns.Add(new DataColumn("TimeStamp", typeof(System.DateTime)));
foreach (DataRow dr in dt.Rows)
{
dr["Email"] = User.Identity.GetUserId();
dr["TimeStamp"] = DateTime.Now.ToString();
}
SqlBulkCopy objbulk = new SqlBulkCopy(con);
objbulk.DestinationTableName = "Upload";
objbulk.ColumnMappings.Add("Email", "Email");
objbulk.ColumnMappings.Add("TimeStamp", "TimeStamp");
objbulk.ColumnMappings.Add("EmployeeId", "EmployeeId");
objbulk.ColumnMappings.Add("Name", "Name");
objbulk.ColumnMappings.Add("Title", "Title");
objbulk.ColumnMappings.Add("Department", "Department");
objbulk.ColumnMappings.Add("Race", "Race");
objbulk.ColumnMappings.Add("Gender", "Gender");
objbulk.ColumnMappings.Add("AnnualizedBase", "AnnualizedBase");
objbulk.ColumnMappings.Add("AnnualizedTCC", "AnnualizedTCC");
con.Open();
objbulk.WriteToServer(dt);
con.Close();
}
}
}
Thanks!
In a cloud environment you typically don't write to the web server file system. Rather, you save the upload off to blob storage and keep a record of the path where you saved it along with the persisted data record.
Here is an article where the author uses the Storage APIs to send an uploaded image off to a blob. But this is a rather standard challenge to solve with blob storage, so the Microsoft documentation will likely provide enough information for you to make progress. Here is an official Microsoft sample MVC controller that combines MVC and blob storage.

how to insert data from csv file into database using 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.

Database does not exist

Here is my code to back up a database.
These are my databases:
I got this as Error:
Database 'BakupDB' does not exist. Make sure that the name is entered
correctly. BACKUP DATABASE is terminating abnormally.
And the code for my web page:
public partial class Default2 : System.Web.UI.Page
{
string dbname = "BakupDB";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
//Mentioned Connection string make sure that user id and password sufficient previlages
sqlcon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True";
//Enter destination directory where backup file stored
string destdir = "D:\\backupdb";
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database "+dbname+" to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
Response.Write("Backup database successfully");
}
catch (Exception ex)
{
Response.Write("Error During backup database!");
}
}
}
What do I wrong?
It looks like you're trying to use a User Instance. As an aside (not 100% related to your question) I believe that this feature is deprecated in SQL Server Express 2012 (and have been on a deprecation path since SQL Server 2008).
Sorry for the aside. With regards to your question perhaps the following will help you:
Stack Overflow question
Accomplishing the task using SMO
I would say the Stack Overflow question is closer to the use case you're trying to achieve with executing the SQL command, but have referenced the SMO way in case you were interested or wanted to try a different approach. Based on the SO question it appears that your connection string:
sqlcon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True";
Is missing a Database= section so perhaps it should read like:
sqlcon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True;Database=BakupDB";
This code worked for me:
private void button5_Click(object sender, EventArgs e)
{
try
{
string dlink= #"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\jsdb.mdf; Database=jsdb; User Instance=True; Integrated Security=True;Asynchronous Processing= True";
SqlConnection dcc = new SqlConnection(dlink);
dcc.Open();
string database = "jsdb";
string blc = textBox1.Text; //(Its the location to save the file)
string nm = "dbBackup";
string dt =DateTime.Today.ToShortDateString();
string sl = "BACKUP DATABASE "+database+" TO DISK = '"+blc+"\\"+nm+"-"+dt+".bak'" ;
SqlCommand cql = new SqlCommand(sl,dcc);
cql.ExecuteNonQuery();
MessageBox.Show("Database backup completed successfully..");
dcc.Close();
}
catch (Exception ex)
{ MessageBox.Show(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.

Resources