Writing DataReader Rows to Excel File - asp.net

I've got data in SQL Server 2000 and have a HyperLink that goes to a pass-through form whose code-behind will output the data to an Excel file. I've been following this tutorial:
http://www.dzone.com/links/r/export_gridview_to_excelcsv_in_net_using_c.html
I have succeeded in outputting some sample values from the DataReader. First problem I'm encountering is that there is no DataTable Load method in 1.1. I have data coming back via the DataReader but what I need help with is how to create the headers and output them, along with the rows of data, to the Excel file...
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
string attachment
= "attachment;filename=Report_" + DateTime.Now.ToString() + ".xls";
Response.AddHeader("content-disposition", attachment);
Response.Charset = string.Empty;
Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
Response.ContentType = "application/ms-excel";
DataTable dt = new DataTable();
dt.Columns.Add("Company");
dt.Columns.Add("Address1");
dt.Columns.Add("Address2");
dt.Columns.Add("City");
dt.Columns.Add("State");
dt.Columns.Add("ZipCode");
SqlConnection con = new SqlConnection();
SqlCommand com = new SqlCommand();
con.ConnectionString = "myconnstring";
com.Connection = con;
com.CommandText
= "SELECT DISTINCT Company, Address1, Address2, City, State, ZipCode" +
" FROM Vendor_View";
con.Open();
SqlDataReader dr = com.ExecuteReader();
while(dr.Read())
{
// how to grab and output data to Excel?
}

I myself wrote a blog post about this. Basically there are 3 alternatives. But I recommend this one:
//Make sure you add this reference and have it imported
Using Excel = Microsoft.Office.Interop.Excel;
protected void xlsWorkBook()
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = “Customers”;
// Process the DataTable
// BE SURE TO CHANGE THIS LINE TO USE *YOUR* DATATABLE
//DataTable dt = Customers.RetrieveAsDataTable();//commented
DataTable dt = Table;//added
Session["dt"] = dt;//added
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[1, 1],
oSheet.Cells[rowCount, dt.Columns.Count]);
oRange.EntireColumn.AutoFit();
// Save the sheet and close
oSheet = null;
oRange = null;
oWB.SaveAs(“test.xls”, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}

If it's simple data, then just emit a CSV file. Excel can be configured to open those pretty easily.
Something like the following would get you started:
response.ContentType = "text/csv";
response.AddHeader("Content-Disposition", "attachment;filename=report.csv;");
response.AddHeader("Pragma", "no-cache");
response.AddHeader("Expires", "0");
// 1. output columns
Boolean addComma = false;
response.Write("\"");
foreach (DataColumn column in _dataToProcess.Columns) {
if (addComma) {
response.Write("\",\"");
} else {
addComma = true;
}
response.Write(column.ColumnName.ToString());
} // foreach column
response.Write("\"");
response.Write(System.Environment.NewLine);
// 2. output data
foreach (DataRow row in _dataToProcess.Rows) {
addComma = false;
response.Write("\"");
foreach (Object value in row.ItemArray) {
// handle any embedded quotes.
String outValue = Convert.ToString(value).Replace("\"", String.Empty);
if (addComma) {
response.Write("\",\"");
} else {
addComma = true;
}
response.Write(outValue);
}
response.Write("\"");
response.Write(System.Environment.NewLine);
} // foreach row

Related

How to create multiple CSV file in 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);
}

how to export sql table to excel without loss your formatting?

I want export sql table to excel file.
my Code:
public void ExportToExcel(string strQuery)
{
//Get the data from database into datatable
OleDbCommand cmd = new OleDbCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
HttpContext.Current.Response.Write(style);
HttpContext.Current.Response.Output.Write(sw.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
and In Button of aspx page:
protected void ExportToExcel(object sender, EventArgs e)
{
ExportClass Exc = new ExportClass();
string wherestr = null;
if ((StartTBX.Text.Length > 0) && (EndTBX.Text.Length > 0)) { wherestr = String.Format("((STATUS = 'User' And PostStatus='Default') or STATUS = 'Admin') And (CreateDate >='{0}' And CreateDate <='{1}')", StartTBX.Text, EndTBX.Text); }
else if (StartTBX.Text.Length > 0) { wherestr = String.Format("((STATUS = 'User' And PostStatus='Default') or STATUS = 'Admin') And CreateDate >='{0}'", StartTBX.Text); }
else if (EndTBX.Text.Length > 0) { wherestr = String.Format("((STATUS = 'User' And PostStatus='Default') or STATUS = 'Admin') And CreateDate <='{0}'", EndTBX.Text); }
else { wherestr = "((STATUS = 'User' And PostStatus='Default') or STATUS = 'Admin')"; }
Exc.ExportToExcel("SELECT Users.UserID, UserName, Status, LockUser, FName + ' ' + Lname as [نام کامل] FROM Users inner join UsersInfo on Users.UserID=UsersInfo.UserID WHERE " + wherestr + " ORDER BY CreateDate DESC");
}
When I do not use date filtering in code(last else in code), every thing is fine but when i use date filtering, the content of [نام کامل] format is lost. content of [نام کامل] is Non-English words.
without date filter:
with date filter:
Please help me. Thank a lot.
well, my problem resolve with this code:
HttpContext.Current.Response.ContentEncoding = Encoding.Unicode;
HttpContext.Current.Response.BinaryWrite(Encoding.Unicode.GetPreamble());
best regards.

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.

How to fix "Microsoft Office Excel cannot open or save any more documents because there is not enough available memory or disk space"?

I am trying to export a dataset in my website to excel.
The code is working fine on local machine but when I am deploying the same to win. server im getting following error :
I am using following code :
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
SqlConnection con = new SqlConnection(constr);
con.Open();
string sql = "SELECT * FROM Table1";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter adptr = new SqlDataAdapter();
adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();
ds.Tables.Add(dt);
MyExcel.Application oXL;
MyExcel.Workbook oWB;
MyExcel.Worksheet oSheet;
MyExcel.Range oRange;
// Worksheets sheets = excelApp.Worksheets; // <-- the important part
//Worksheet sheet = sheets.Open(...);
oXL = new MyExcel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
oWB = oXL.Workbooks.Add(System.Type.Missing);
//oWB = oXL.Workbooks.Add(System.Type.Missing);
oSheet = (MyExcel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "Customers";
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[1, 1],
oSheet.Cells[rowCount, dt.Columns.Count]);
oRange.EntireColumn.AutoFit();
// Save the sheet and close
oWB.SaveAs("test.xlsx", MyExcel.XlFileFormat.xlWorkbookNormal, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing,
MyExcel.XlSaveAsAccessMode.xlExclusive, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
oSheet = null;
oRange = null;
oWB = null;
oXL = null;
oWB.Close(false, System.Type.Missing, System.Type.Missing);
Marshal.FinalReleaseComObject(oWB);
Marshal.FinalReleaseComObject(oXL);
oXL.Quit();
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oSheet);
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
I am not getting any fix for this. Can anyone help ?
If you have checked that you have enough free space available then the only other issue it could be is permissions.
Hope you find this link useful:
http://www.codeproject.com/Questions/87128/Unable-to-write-data-runtime-in-Excel-app-using-c

how to Design the exported excel in asp.net?

I am exporting gridview data to excel but that excel file add the some lable text and textbox values and format also taken , pls give how to design the excel code in asp.net. I am writing like this
All gridview data taken dataset ds
-pls give me textbox values and some label or normal text designed code in excel
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = ds;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=DataTable.xls");
Response.Charset = string.Empty;
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
////Apply text style to each Row
GridView1.Rows[i].Cells[4].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:'\#,\#\#0\.00';}
.textmode1(mso-number-format:'\#';}
.SSNmode{mso-number-format:'000-00-000';} </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
Take a look at this awesome tool: http://www.carlosag.net/Tools/ExcelXmlWriter/
Futhermore, the author also created a code generator, which generates .net code from a provided excel sheet(formatting, layout and so on)
http://www.carlosag.net/Tools/ExcelXmlWriter/Generator.aspx
Here's some code that generates an excel file from a datatable (converted vb code, as pr. request by poster)
CarlosAg.ExcelXmlWriter.Workbook book = new CarlosAg.ExcelXmlWriter.Workbook();
book.ExcelWorkbook.ProtectWindows = false;
book.ExcelWorkbook.ProtectStructure = false;
var styles = book.Styles;
WorksheetStyle defaultStyle = styles.Add("Default");
var defStyles = defaultStyle;
defStyles.Name = "Normal";
defStyles.Font.FontName = "Calibri";
defStyles.Font.Size = 11;
defStyles.Font.Color = "#000000";
defStyles.Alignment.Vertical = StyleVerticalAlignment.Bottom;
Worksheet sheet = book.Worksheets.Add("Sheet1");
sheet.Table.DefaultRowHeight = 15f;
sheet.Table.FullColumns = 1;
sheet.Table.FullRows = 1;
DataTable dt = new DataTable(); //= your datatable
//Header
WorksheetRow HeaderRow = sheet.Table.Rows.Add();
foreach (DataColumn col in dt.Columns)
{
HeaderRow.Cells.Add(col.ColumnName.ToString());
}
//Body
foreach (DataRow dr in dt.Rows)
{
WorksheetRow row = sheet.Table.Rows.Add();
foreach (DataColumn cols in dt.Columns)
{
row.Cells.Add(dr[cols.ColumnName.ToString()].ToString());
}
}
sheet.Options.Selected = true;
sheet.Options.ProtectObjects = false;
sheet.Options.ProtectScenarios = false;
book.Save("path to file");

Resources