How to create multiple CSV file in ASP .Net - asp.net

I want to create multiple CSV file for every drop down Selected value. Even-though while debugging i can notice csv is appending for different drop down value but not writing another CSV file. do not know why and where i am doing mistake.
When i remove using block, and for second time its throwing error :
The process cannot access the file 'File path' because it is being used by another process.
I believe need to store all files on server but again same issue
i have added code to solve error but no change;
if (File.Exists(filePath))
File.Delete(filePath);
Button code
protected void btnGenerate_Click(object sender, EventArgs e)
{
List<int> stopWordArray = new List<int>();
foreach (ListItem listItem in ddlDepot.Items)
{
if (listItem.Selected)
{
string FileType = ddlqoutatfileType.SelectedItem.Text;
DateTime Qotation_Date = Convert.ToDateTime(txtdate.Text).AddDays(3);
var Qotation_Date_modified = Qotation_Date.ToShortDateString();
OracleCommand CmdB = new OracleCommand("Select DEPOT_CODE, PRODUCT_CODE, TO_CHAR(TO_DATE(UPLOAD_DATE,'DD/MM/YYYY'), 'DDMMYYY') as UPLOAD_DATE , TO_CHAR(TO_DATE(SALES_DATE,'DD/MM/YYYY'), 'DDMMYYYY') as SALES_DATE, ORDER_QTY, FILE_TYPE, ROUTE_CODE from SCM_SARAS_ORDERS_vw where File_Type = '" + FileType + "' and DEPOT_CODE =" + listItem.Value + " and SALES_DATE = TO_DATE('" + Qotation_Date_modified + "' , 'DD/MM/YYYY')", con);
CmdB.CommandType = CommandType.Text;
OracleDataAdapter daB = new OracleDataAdapter();
DataTable dtB = new DataTable();
daB.SelectCommand = CmdB;
daB.Fill(dtB);
string csv = string.Empty;
foreach (DataRow row in dtB.Rows)
{
foreach (DataColumn column in dtB.Columns)
{
csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
}
csv += "\r\n";
}
string fileName = "myfile.csv";
string filePath = Server.MapPath("~/file" + fileName);
using (StreamWriter sw = new StreamWriter(filePath, false))
{
sw.Write(csv);
}
}
}
}

I am not sure what do you mean about follow problem.
#but not writing another CSV file#
in your code, obviously, you wrote same file in the loop; why do not you change it to
string fileName = "myfile"+listItem.Value+".csv";//change filename?
string filePath = Server.MapPath("~/file" + fileName);
using (StreamWriter sw = new StreamWriter(filePath, false))
{
sw.Write(csv);
}

Related

How can I remove a CSV's header when importing it to a gridview?

I would like to ask if you have a source code for importing csv files to gridview in an ASP.NET web form.
What I want to do is remove the header on the file and display it in the grid view.
Here is a SC of my file
Read the CSV into a DataTable and then bind it into the GridView:
public void bindGrid()
{
var dt=GetDataTableFromCsv("path_to_csv_file",true);
GridView1.DataSource=dt;
GridView1.DataBind();
}
From How to read a CSV file into a .NET Datatable:
DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = #"SELECT * FROM [" + fileName + "]";
using(OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
using(OleDbCommand command = new OleDbCommand(sql, connection))
using(OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}

.xslx import error The 'Microsoft.ACE.OLEDB.12.0' in asp .net

.xslx import error The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine. IN SERVER(godaddy webserver)..
there are lot of blog telling to install software..2010 and 2007 oledb connection software..
my system is product 32 bit(x86) architecture and 64bit architecture.
I have tried almost 2 days the problem is that in localhost both .xls and .xlsx import working fine..but while i am using server there is the problem while on .xlsx files only..
so which dll need to put on bin folder of server so that i can solve the problem in server..
Here is the code:
if (flexcel.HasFile)
{
name = rnd.Next(111, 9999).ToString() + "_" + System.IO.Path.GetFileName(flexcel.FileName);
string fileExtension = System.IO.Path.GetExtension(flexcel.FileName);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
string fileLocation = Server.MapPath("../Content/MailMarketing/") + name;
if (System.IO.File.Exists(fileLocation))
{
// System.IO.File.Delete(fileLocation);
}
flexcel.SaveAs(fileLocation);
string excelConnectionString = string.Empty;
//excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
//Server.MapPath("~/Content/MailMarketing/" ) + flexcel.FileName + month + ";Extended Properties=\"Excel 12.0;\"";
////connection String for xls file format.
if (fileExtension == ".xls")
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;\"";
}
//connection String for xlsx file format.
else
//if (fileExtension == ".xlsx")
{
excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
Server.MapPath("../Content/MailMarketing/" + name) + ";Extended Properties=Excel 12.0;";
}
//Create Connection to Excel work book and add oledb namespace
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
//excel data saves in temp file here.
foreach (DataRow row in dt.Rows)
{
string x = row["TABLE_NAME"].ToString();
if (x != "Sheet1$_" && x != "Sheet2$_" && x != "Sheet3$_" && x != "Sheet4$_" && x != "Sheet5$_")
{
excelSheets[t] = row["TABLE_NAME"].ToString();
t++;
}
}
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
int totalsheet = excelSheets.Length;
for (int i = 0; i < totalsheet; i++)
{
string query = string.Format("Select * from [{0}]", excelSheets[i]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
}
}
if (fileExtension.ToString().ToLower().Equals(".xml"))
{
string fileLocation = Server.MapPath("~/Content/") + Request.Files["FileUpload"].FileName;
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
Request.Files["FileUpload"].SaveAs(fileLocation);
XmlTextReader xmlreader = new XmlTextReader(fileLocation);
// DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
}
Any suggestions??
Without installing software can anyone suggest me which type of .dll files need to put on the bin folder??
No need to worry about only oledb..there is a lot of other method are used to upload .xlsx files(import).
Here is the header:
using ClosedXML.Excel;
Install ClosedXML.Excel dll from nuget.
Here is the code:
string filePath = Server.MapPath("~/Content/MailMarketing/") + Path.GetFileName(flexcel.PostedFile.FileName);
flexcel.SaveAs(filePath);
//Open the Excel file using ClosedXML.
using (XLWorkbook workBook = new XLWorkbook(filePath))
{
//Read the first Sheet from Excel file.
IXLWorksheet workSheet = workBook.Worksheet(1);
//Create a new DataTable.
DataTable dt = new DataTable();
//Loop through the Worksheet rows.
bool firstRow = true;
foreach (IXLRow row in workSheet.Rows())
{
//Use the first row to add columns to DataTable.
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
dt.Columns.Add(cell.Value.ToString());
}
firstRow = false;
}
else
{
//Add rows to DataTable.
dt.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells())
{
dt.Rows[dt.Rows.Count - 1][i] = cell.Value.ToString();
i++;
}
}
}

How to update sql database table info with excel file using file uploaded

I am trying to update the files in the table that I have created. I am using file uploader to insert my Excel file and upload it to the database. But currently my code creates a new database table each time a file is uploaded, which I don't want it to do. I want to just update/replace the whole file in database table. How do I do this?
This is my code:
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["nConnectionString2"].ConnectionString;
}
private void CreateDatabaseTable(DataTable dt, string tableName)
{
string sqlQuery = string.Empty;
string sqlDBType = string.Empty;
string dataType = string.Empty;
int maxLength = 0;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName));
for (int i = 0; i < dt.Columns.Count; i++)
{
dataType = dt.Columns[i].DataType.ToString();
if (dataType == "System.Int32")
{
sqlDBType = "INT";
}
else if (dataType == "System.String")
{
sqlDBType = "NVARCHAR";
maxLength = dt.Columns[i].MaxLength;
}
if (maxLength > 0)
{
sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength));
}
else
{
sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType));
}
}
sqlQuery = sb.ToString();
sqlQuery = sqlQuery.Trim().TrimEnd(',');
sqlQuery = sqlQuery + " )";
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
{
string sqlQuery = string.Empty;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName));
sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath));
sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter));
sqlQuery = sb.ToString();
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName);
if (fileInfo.Name.Contains(".csv"))
{
string fileName = fileInfo.Name.Replace(".csv", "").ToString();
string csvFilePath = Server.MapPath("UploadExcelFile") + "\\" + fileInfo.Name;
//Save the CSV file in the Server inside 'MyCSVFolder'
FileUpload1.SaveAs(csvFilePath);
//Fetch the location of CSV file
string filePath = Server.MapPath("UploadExcelFile") + "\\";
string strSql = "SELECT * FROM [" + fileInfo.Name + "]";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'";
// load the data from CSV to DataTable
OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString);
DataTable dtCSV = new DataTable();
DataTable dtSchema = new DataTable();
adapter.FillSchema(dtCSV, SchemaType.Mapped);
adapter.Fill(dtCSV);
if (dtCSV.Rows.Count > 0)
{
CreateDatabaseTable(dtCSV, fileName);
Label1.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName);
string fileFullPath = filePath + fileInfo.Name;
LoadDataToDatabase(fileName, fileFullPath, ",");
Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName);
}
else
{
Label1.Text = "File is empty.";
}
}
else
{
Label1.Text = "Unable to recognize file.";
}
}
}
The code that creates the tables should give an error when you run it if the tables already exists as you never drop them.
That said, one solution might be to add a check to see if the table already exists in the code that creates a new table; it should be something like:
IF OBJECT_ID('TABLE', 'U') IS NULLwhere TABLEit the name of the table that you want to add, so the code might look like:
sb.AppendFormat(string.Format("IF OBJECT_ID({0}, 'U') IS NULL CREATE TABLE {0} (", tableName));
Another, possibly better, option would be to run a query to check if the table exists before you run the CreateDatabaseTable(dtCSV, fileName);statement. You can do the check by executing something like IF OBJECT_ID('tableName', 'U') IS NULL SELECT 1 ELSE SELECT 0 (this would return 1 if the table doesn't exist), and then conditionally execute the CreateDatabaseTablestatement.

Employee ID reflected in created by column instead of display name

I wrote a program to import data from excel sheet to sharepoint 2007 list. Around 11000 data gets imported. I have used the below code. My query is I wanted to put "employee's display name" in "created by" column. And im providing the same in excel sheet n in the code. But after the data gets imported I see that few employees data has reflected the created by column with their names. But for few it reflects EMPID only or EMPID + name. I debug the code It takes the right string to display but i did not understand y it gives such results. Also i am running the prog on my machine n not the server, so is it bcoz of this. As I am using test server and then only will deploy to production.
Code:
protected void btnImport_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("URL"))
{
using (SPWeb web = site.OpenWeb())
{
webapp = web.Site.WebApplication;
webapp.FormDigestSettings.Enabled = false;
SPList list = web.Lists["List name"];
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\Test.xlsx;Extended Properties=Excel 12.0";
OleDbConnection oledbConn = new OleDbConnection(connString);
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);//contents from sheet1 is selected
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "Employees");
DataTable dt = ds.Tables["Employees"];
DataView dv = new DataView(dt);
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite elevatedSite = new SPSite("URL"))
{
elevatedRootWeb = elevatedSite.OpenWeb();
}
});
foreach (DataRowView drv in dv)
{
EMPID = drv["Emp id"].ToString();
DispName = drv["Name"].ToString();
Title = drv["Title"].ToString();
getid = new SPQuery();
getid.Query = "<Where><Eq><FieldRef Name=’EMPID’ /><Value Type='Text'>" + EMPID + "</Value></Eq></Where><OrderBy><FieldRef Name='ID'/></OrderBy>";
check = list.GetItems(getid).GetDataTable();
if (check == null)
{
try
{
elevatedRootWeb.AllowUnsafeUpdates = true;
UserItem = list.Items.Add();
UserItem["Emp id"] = EMPID;
UserItem["Title"] = Title;
test = elevatedRootWeb.EnsureUser(PSNumber).ID + ";#" + DispName;
UserItem["Author"] = test;
UserItem.Update();
list.Update();
count++;
elevatedRootWeb.AllowUnsafeUpdates = false;
using (StreamWriter w = File.AppendText("D:\\Errorlog_SP2010.txt"))
{
Log(PSNumber + "Inserted successfully", w);
w.Close();
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("<script>alert('Exception on adding item " + ex.Message + "')</script>");
using (StreamWriter w = File.AppendText("D:\\Errorlog_SP2010.txt"))
{
Log(ex.ToString()+ PSNumber, w);
w.Close();
}
}
}
check the "_catalogs/users/simple.aspx" list to see if the user on that site has thier information stored correctly.
This is important as the Author field takes it's value from what is displayed in this list, not exactly what you set.
See this question on how to fix this.

OleDb - Retrieving Excel worksheet names also retrieves Defined Names

I am trying to retrieve a list of the worksheets in an Excel workbook, but the collection I get back has both the sheet names and the data column id's, which seem to be called 'Defined Names' in the original xlsx xml. Can you tell me how to return only the worksheet names?
The code I'm using is along the lines of:
OleDbConnection connExcel = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;"
+ #"Data Source=" + FilePath + ";"
+ #"Extended Properties=""Excel 8.0;HDR=Yes;""");
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.Connection = connExcel;
connExcel.Open();
DataTable testTable = connExcel.GetSchema("Tables");
The contents of the resulting testTable collection contain entries under TABLE_NAME of:
DATA1
DATA2
DATA3
DATA4
DATA5
Sheet1$
TEST1
-TEST2
TESTHKEY
TESTKEYS
TESTVKEY
They all have a TABLE_TYPE of TABLE.
The original workbook corresponding to the above would have 1 worksheet containing 5 columns, the first row would contain a header. I'm only interested in the Sheet1$ entry. The spreadsheet is
created in Excel 2010, I'm trying to process it in an ASP.NET 4 app written in C#. Potentially, the worksheet name may have been changed so I can't guarrantee that it will always be Sheet1$.
My first thoughts were wrong so I came up with this as a workaround. The actual worksheet names returned should always end with $, so I hacked it to check for that. Messy but you get the general idea I'm sure.
OleDbConnection connExcel = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;"
+ #"Data Source=c:\test.xlsx;"
+ #"Extended Properties=""Excel 12.0 Xml;HDR=Yes;""");
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.Connection = connExcel;
connExcel.Open();
DataTable testTable = connExcel.GetSchema("Tables");
String[] excelSheets = new String[testTable.Rows.Count];
int i = 0;
foreach (DataRow row in testTable.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
if (excelSheets[i].EndsWith("$"))
{
Console.WriteLine(excelSheets[i] = row["TABLE_NAME"].ToString());
i++;
}
else
{
i++;
}
}
Console.ReadLine();
I had a similar issue but with the exception that it showed me Sheets that didn't exist in Excel. Even though this post is a bit old now, maybe somebody finds this and finds it helpful.
My Code:
//OpenFileDialog
try
{
OpenFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
OpenFileDialog.Filter = "XLSX Files(*.xlsx)|*.xlsx|All Files (*.*)|*.*";
OpenFileDialog.ShowDialog();
}
catch (Exception ex)
{
//some Error Message
}
//read into Combobox
try
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + OpenFileDialog.FileName + ";Extended Properties=Excel 12.0;");
con.Open();
DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
con.Close();
this.Combobox.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
String sheetName = dt.Rows[i]["TABLE_NAME"].ToString();
sheetName = sheetName.Substring(0, sheetName.Length - 1);
//cheap Filter to filter out unneeded/wrong sheets
if (sheetName.Replace("'", " ").Replace("$", " ").TrimStart().TrimEnd().Contains("#") != true)
{
this.Combobox.Items.Add(sheetName.Replace("'", " ").Replace("$", " ").TrimStart().TrimEnd());
}
}
}
catch (Exception Ex)
{
//some Error Message
}
This might not be the best solution, but it works quite well for me.
private static string EXCEL_CONNECTIONSTRING = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; data source={0}; Extended Properties=Excel 12.0;", "#{FILENAME}");
private IEnumerable<string> GetWorksheetNames(string excelFile)
{
var currentConnectionString = EXCEL_CONNECTIONSTRING.Replace("#{FILENAME}", excelFile);
using (OleDbConnection connection = new OleDbConnection(currentConnectionString))
{
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.Connection = connection;
connection.Open();
DataTable dt = connection.GetSchema("Tables");
IEnumerable<string> excelSheets = dt.Rows.Cast<DataRow>().Select(row => row["TABLE_NAME"].ToString());
dt.Dispose();
connection.Close();
return excelSheets;
}
}

Resources