I have a process that allows the user to download a spreadsheet, make some changes, and then upload those changes.
The upload method looks like -
public DataTable ImportXLS(String SourceFilePath) {
string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + SourceFilePath + ";" +
"Extended Properties=Excel 8.0;";
using (OleDbConnection cn = new OleDbConnection(ConnectionString)) {
cn.Open();
DataTable dbSchema = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1) {
throw new Exception("Error: Could not determine the name of the first worksheet.");
}
string WorkSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + WorkSheetName + "]", cn);
DataTable dt = new DataTable(WorkSheetName);
da.Fill(dt);
return dt;
}
}
When I call the method locally, it works because I can see my local drives.
When deployed to the web server, and called like -
ExportImport _ei = new ExportImport();
DataTable dt = null;
dt = _ei.ImportXLS("C:\Users\mike\Desktop\mike.xls");
I get an error that "C:\Users\mike\Desktop\mike.xls" is not a valid path, obviously because it doesn't exist on the web server.
Has anyone had any experience with trying to upload files over the web and how do you resolve the file location issue?
You need to add a FileUpload control to your Asp.Net page. On a button click you need to the save the file on the server by calling:
FileUpload1.SaveAs("C:\\Uploads\\" + FileUpload1.FileName);
Afterwards you can call you method to process the file
ExportImport _ei = new ExportImport();
DataTable dt = null;
dt = _ei.ImportXLS("C:\\Uploads\\" + FileUpload1.FileName);
So the idea is to upload the file first to the server before processing it.
A link on using the FileUpload control (.Net 2.0)
http://msdn.microsoft.com/en-us/library/aa479405.aspx
You can use Server.MapPath to get the virtual location of your app. Have a look at this article.
Related
I tried to convert excel file to XML file. And I did it successfully. However when I run the APP on another PC (where I dont have SQL server manager), it is not working anymore. I receive this error
'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine
which I tried to solve with every solved question here (installing Microsoft Access Database Engine 2016 Redistributable, converting app into x86, etc...) and nothing worked.
But since I don't really need (or at least I think so) Access, is there any other way, how to convert excel file to xml?
Here is to code
XmlDocument doc = new XmlDocument();
try
{
bool test = Environment.Is64BitProcess;
FileName.Content = filelocation.Substring(filelocation.LastIndexOf(#"\")+1);
if (!test)
{
connStr = "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=" + filelocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection conn = new OleDbConnection(connStr);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
To here it is working, here is the issue
conn.Open();
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = dtSheet.Rows[0]["table_name"].ToString();
cmd.CommandText = "select * from [" + sheetName + "]";
da.SelectCommand = cmd;
da.Fill(dt);
conn.Close();
And then I continue...
DataSet ds = new DataSet();
ds.Tables.Add(dt);
oItem = dt.Rows.Count;
oItem -= 1;
XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
declaire.Standalone = "yes";
XmlElement rootnode = doc.CreateElement("Wiring");
doc.InsertBefore(declaire, doc.DocumentElement);
doc.AppendChild(rootnode);
while (i <= oItem)
{
XmlElement dobEle = doc.CreateElement("Machine");
do
{...
Is there any other way how to solve the problematic code?
EDIT
I have installed Office on both PCs. And I have tried .Ace.OLEDB.x (4-23 [just to be sure]) and on PC where I develop the APP v.12 and v.16 works. On the PC where I deployed the app none of them works
Edit 2 So I just found out I have office 365 on the 2nd computer but not fully licensed Access (for whatever reason). Could someone confirm, if that's the reason why it doesn't work?
simple and easy excel file reader.
https://github.com/ExcelDataReader/ExcelDataReader
i believe u can also add it from nuget
I'm frustrated because i can't solve this problem...
Well, i has been making a desktop application in C#, i almost complete the application,
But i have a big problem.
My application import an excel workbook who has some information that it is showed in a Gridview.
It works ok, but my app update or modified the data that is showed in a gridview, only one column that is called Balance.
I want to update this column in my excel workbook, is like an update condition in SQL, for example
I have this information that is imported to my app.
If i modify in my app some row, for example the row that has the order "12345", i want to update in my excel workbook the column called Balance of that row.
I has been trying with this code:
string order = textBox1.Text;
string balance = textBox2.Text;
filePath = openFileDialog1.FileName;
extension = Path.GetExtension(filePath);
header = "Yes";
OleDbConnection MyConnection = new OleDbConnection(conStr); ;
OleDbCommand myCommand = new OleDbCommand();
string sql = null;
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "UPDATE [" + sheetName + "] SET [" + sheetName + "].[Order]=123 WHERE [" + sheetName + "].[Balance]=12313";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
And if i debug the code it is the sentence that is executed, and i think that it is ok, but it doesn't works.
UPDATE ['12234$'] SET ['12234$'].[Order]=123 WHERE ['12234$'].[Balance]=12313
It give me this error:
Message=No value given for one or more required parameters.
Source=Microsoft Access Database Engine
Consider using an NuGet package to work with Excels instead. EPPlus is an excellent one.
using (var package = new ExcelPackage(#"someFile.xlsx")
{
var sheet = package.Workbook.Worksheets.First();
sheet.Cells["E2"].Value = 12345.32M;
package.Save();
}
Sql is no longer possible, but you can use Linq:
using (var package = new ExcelPackage(#"someFile.xlsx")
{
var sheet = package.Workbook.Worksheets.First();
int rowIndex = sheet.Cells["C2:C5"].First(x => int.Parse(x.Value.ToString()) == 12345).Start.Row;
const int balanceColumnIndex = 5;
sheet.Cells[rowIndex, balanceColumnIndex].Value = 12313M;
package.Save();
}
I wrote a series about EPPlus on my blog.
This is just a thought - but is your SQL-like string set up correctly?
If you're trying to update the balance for a certain order, you'd want that to be in your SET command.
So, something along the lines of...
UPDATE ['12234$'] SET ['12234$'].[Balance]=12313 WHERE ['12234$'].[Order]=12345
//try this solution
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Directory.GetCurrentDirectory() + "/swtlist.xlsx;" +
#"Extended Properties='Excel 12.0;HDR=Yes;';Persist Security Info=False;";
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
try
{
DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
OleDbCommand cmd = new OleDbCommand("UPDATE [Feuil1$] SET d='yes' ", connection);
cmd.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex) { }
}
Hi I am having some issues reading a CSV file with the Jet Database engine. I get this message:
The Microsoft Jet database engine cannot open the file 'C:\Users\mikec\Desktop\'. It is already opened exclusively by another user, or you need permission to view its data.
I have permission to access this folder and file. I have also tried putting in my Visual Studio project and still get the same error. This is my code
string path = #"C:\Users\mikec\Desktop\Book1.csv";
string full = Path.GetFullPath(path);
string file = Path.GetFileName(full);
string dir = Path.GetDirectoryName(full);
//create the "database" connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=\"" + dir + "\\\";"
+ "Extended Properties=\"Excel 8.0;HDR=Yes;FMT=Delimited\"";
//create the database query
string query = "SELECT * FROM " + file;
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
OleDbConnection con = new OleDbConnection(connString);
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, con);
try
{
//fill the DataTable
dAdapter.Fill(dTable);
}
catch (InvalidOperationException e)
{
}
I'm confused to why this is happening I've looked around the Internet and cannot find a solution.
It would be great if anyone out there could point me in the right direction.
Thanks.
I'm currently facing a problem whereby I don't know how to fix it.
I upload my precompiled project into IIS. Here is my purpose of this page:
User upload a excel file into a folder in the server. ex #"~/PlanQuantityFile/". It did upload successfully.
Problems faced:
It stops when my scripts trying to open the excel file (for extract data purpose) without showing any errors. At line 881 as shown in the image.
Here is few area I had seek for but it still couldn't solve my problem.
Possible Solution:
connection open but never close, so run out of connection. (but I did close it and the scripts stop running before the close statement)
32 bit program calling 64 bit office. (I had limited knowledge on hardware field, don't know what should I do to troubleshoot here)
permission problem. Need to set the permission of ASP.NET account. (I still finding object names for ASP.NET account)
Thanks for anyone who trying to help. Your advice is invaluable.
OleDbConnection oledbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + SaveLocation + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
OleDbConnection connExcel = oledbConn;
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
//Get the name of Sheet
try
{
connExcel.Open();// It stops here without showing errors.
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
}
The following code returns a datatable for selected filelocation source. Remember to rename the sheetname to "Sheet1".
Use Namespace: using System.Data.OleDb;
Function::::
public DataTable GetExcelinDatatable(string filelocation)
{
DataTable dt = new DataTable();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filelocation + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
con.Open();
OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter("select * from [SHEET1$]", con);
da.Fill(dt);
con.Close();
return dt;
}
you can use mentioned function to read the Excel file you have to just pass the path of excel file
private List<DataTable> readExcel(string strXLS)
{
//DataTable dtExcel = getExcelSheetTable();
List<DataTable> SheetsData = new List<DataTable>();
DataTable dtExcel = new DataTable();
DataTable SocialMediaExcel = new DataTable();
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strXLS + ";Extended Properties=Excel 12.0;";
try
{
OleDbDataAdapter adpt = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connStr);
adpt.Fill(dtExcel);
SheetsData.Add(dtExcel);
}
catch (Exception ex)
{
throw ex;
}
return SheetsData;
}
Hi I am newbie to c# and sharpssh I am trying to export a csv file to sqlite3 database to external device called explor. I have managed to export csv file to local sqlite3 database and able to connect to database using sharpssh to external device but I want to do both at same time. 1)connect to external device 2)export csv file to database/table on the device. Any help would be greatly appreciated.
1.Connection through SHARPSSH
string _ftpURL = #"192.178.0.77"; //(FAKE IP)
string _UserName = "root"; //FAKE User Name of the SFTP server
string _Password = "preethi"; //FAKE Password of the SFTP server
int _Port = 2222; //Port No of the SFTP server (if any)
string _ftpDirectory = "/home/root/systools/WM/WebMobility.db"; //The directory in SFTP server where the files will be uploaded
string LocalDirectory = "I:\\preethi"; //Local directory from where the files will be uploaded
string FileName = "exploretest.csv"; //File name, which one will be uploaded
// IPHostEntry ip = Dns.GetHostEntry(#"1.1.1.2");
Sftp Connection = new Sftp(_ftpURL,_UserName, _Password);
Connection.Connect(_Port);
EXPORTING the CSV FILE
string strFileName = "I:/preethi/exploretest.csv";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(strFileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
DataTable tb = ds.Tables[0];
//SQLiteConnection.CreateFile("MyDatabase.sqlite");
SQLiteConnection m_dbConnection;
m_dbConnection = new SQLiteConnection("Data source = 19.9.9.3; port=2222; database = WebMobility.db; uid=root; pwd=preethi; Convert Zero Datetime=true;");
m_dbConnection.Open();
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var Id = dr["Id"].ToString();
var VRM = dr["VehicleRegistration"].ToString();
var Points = Convert.ToInt32(dr["TicketScore"].ToString());
string sql = "insert into NaughtyList (Id,VRM,Points) values ( '" + Id + "','" + VRM + "'," + Points + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();