Download multiple excel files from the DataTable - asp.net

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.

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 write data into Excel file and save it? EPPlus C#

I have the code to execute multiple stored procedures from SQl. However, I am having an issue on how to write the data from the stored procedures into the Excel file. After writing the data into the excel file, I would like to save the Excel workbook. How can I achieve this? Any help is very much appreciated.
This is what I have so far:
public static void ExecuteStoredProcedures()
{
using (SqlConnection connection = new SqlConnection("Data Source=the connection goes here.."))
{
SqlTransaction transaction;
connection.Open();
transaction = connection.BeginTransaction();
try
{
SqlCommand cmdOne = new SqlCommand("exec ", connection);
SqlCommand cmdTwo = new SqlCommand("exec", connection);
SqlCommand cmdThree = new SqlCommand("exec", connection);
cmdOne.ExecuteNonQuery();
cmdTwo.ExecuteNonQuery();
cmdThree.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
connection.Close();
}
}
}
public static void SaveExcelFile()
{
string SheetLocation = ConfigurationManager.AppSettings["SheetLocation"];
if (!System.IO.Directory.Exists(SheetLocation))
{
System.IO.Directory.CreateDirectory(SheetLocation);
}
ExecuteStoredProcedures(); //Should I call the method to load the data that comes from the stored procedures? Or what should I do to write the data into the file?
var newFile = new FileInfo(#"C:\Users\");
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
xlPackage.Save();
}
}
Get data from stored procedures in the form of a Dataset or DataTables.
Create worksheet:
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
ExcelWorksheet ws = xlPackage.Workbook.Worksheets.Add(AnyName);
}
Loop in Datatable rows and columns like a 2d array and create cells in the worksheet and add data in the created cells:
int rowIndex = 0
foreach (DataRow DataTableRow in dt.Rows)
{
int colIndex = 1;
rowIndex++;
foreach (DataColumn DataTableColumn in dt.Columns)
{
var cell = ws.Cells[rowIndex, colIndex];
cell.Value = DataTableRow[DataTableColumn.ColumnName];
colIndex++;
}
}

How do I change the format of a specific column in EPPlus?

I've used EPPlus to download my datatable from my website / database to an Excel sheet and the first picture is the result I get. The second picture is what I would like it to be.
Questions:
How do I change the format of my Timestamp to "time"?
Obviously title would still be a string format.
How do I make the width of the columns to match the longest word inside?
So that 80% of the message isn't hidden and you have to drag the column out to read the entire message.
Edit: Completely forgot to add my code...
public ActionResult ExportData()
{
DataTable dataTable = GetData();
using (ExcelPackage package = new ExcelPackage())
{
var ws = package.Workbook.Worksheets.Add("My Sheet");
//true generates headers
ws.Cells["1:1"].Style.Font.Bold = true;
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
ws.Cells[ws.Dimension.Address].AutoFitColumns();
var stream = new MemoryStream();
package.SaveAs(stream);
string fileName = "Log.xlsx";
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
stream.Position = 0;
return File(stream, contentType, fileName);
}
}
public DataTable GetData()
{
DataTable dt = new DataTable();
if (ModelState.IsValid)
{
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MySqlConnection"].ConnectionString))
{
using (SqlCommand comm = conn.CreateCommand())
{
comm.Parameters.AddWithValue("#val1", Session["myID"]);
comm.Parameters.AddWithValue("#val2", "%" + Session["mySearchString"] + "%");
comm.CommandText = "SELECT * FROM dbo.Log WHERE CustomerId = #val1 AND Message LIKE #val2";
try
{
conn.Open();
dt.Load(comm.ExecuteReader());
}
catch (SqlException e)
{
throw new Exception(e.ToString());
}
}
}
}
return dt;
}
Just need to set the Numberformat.Format string. Like this:
ws.Column(2).Style.Numberformat.Format = "hh:mm:ss";
If you want to customize the actual just there are plenty of resource online like http://www.ozgrid.com/Excel/excel-custom-number-formats.htm. Or you can just open it in excel, set the format to Custom and experiment with the string.

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.

ASP .NET Dataset to XML: Storage and Reading

[Below is the almost full Code modified. Currently shows illegal character error when being read].
I have a C# ASP.NET application which is currently reading an XML file from the file system and then loading it into a GridView control. In the grid I can Delete rows. There is also an file upload button below the grid which upload PDF files and they show up in the grid. My code is basically a modified version of this code
The next stage of my work involves reading the XML data as String from a database field--instead of from the XML file. For that to happen, I think I can start out by just reading from the XML file, making changes in the aspx page, and the writing the 'dataset' into a database field called 'PDF_Storage'. How can I do that. Crucially, I need to be able to convert the dataset into some kind of string format for storage. Here is my code snippet.
My database is Oracle 10 but I can figure out the Update sql syntax.
SAMPLE XML FILE:
<DataSet>
<PDF>
<pdf>MyPDF1.pdf</pdf>
</PDF>
<PDF>
<pdf>MyPDF2.pdf</pdf>
</PDF>
<PDF>
<pdf>MyPDF3.pdf</pdf>
</PDF>
</DataSet>
And the corresponding code:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Oracle.DataAccess.Client;
using System.Web.Configuration;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;
public partial class XMLGridTest : System.Web.UI.Page
{
public static string GetConnString()
{
return WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
void binddata()
{
DataSet ds = new DataSet();
// ds.ReadXml(Server.MapPath("testxml.xml"));
String strConnect = GetConnString();
OracleConnection oracleConn = new OracleConnection();
oracleConn.ConnectionString = strConnect;
oracleConn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PDF_Storage FROM CampusDev.CU_POLY WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
//## Line Below as the 'illegal characters' problem###
ds.ReadXml(reader[0].ToString(), XmlReadMode.IgnoreSchema);
gv.DataSource = ds;
gv.DataBind();
}
else
{
// Response.Write(reader.GetString(1));
// TextBox1.Text = reader.GetString(1);
}
}
// gv.DataSource = ds;//##Hard coded for XML. Works!
// gv.DataBind();
//Finally, close the connection
oracleConn.Close();
}
protected void Canceldata(object s, GridViewCancelEditEventArgs e)
{
gv.EditIndex = -1;
binddata();
}
protected void pageddata(object s, GridViewPageEventArgs e)
{
gv.PageIndex = e.NewPageIndex;
binddata();
}
protected void insert(object sender, EventArgs e)
{
/////////////////////////////////File Upload Code/////////////////////////////////
// Initialize variables
string sSavePath = "ParcelPDF/"; ;
if (fileupload.PostedFile == null)
{
Label1.Text = "Must Upload a PDF file!";
return;
}
HttpPostedFile myFile = fileupload.PostedFile;
int nFileLen = myFile.ContentLength;
// Check file extension (must be JPG)
if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".pdf")
{
Label1.Text = "The file must have an extension of .pdf";
return;
}
// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);
// Make sure a duplicate file doesn’t exist. If it does, keep on appending an incremental numeric until it is unique
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + ".pdf";
}
// Save the stream to disk
System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename), System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();
binddata();
DataSet ds = gv.DataSource as DataSet;
DataRow dr = ds.Tables[0].NewRow();
// dr[0] = pdf.Text;
dr[0] = sFilename.ToString();
ds.Tables[0].Rows.Add(dr);
ds.AcceptChanges();
string blah = "blah";
Response.Write(ds.Tables.ToString());
// ds.WriteXml(Server.MapPath("testxml.xml"));
String strConnect = GetConnString();
OracleConnection oracleConn = new OracleConnection();
oracleConn.ConnectionString = strConnect;
oracleConn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.Text;
// cmd.CommandText = "SELECT OBJECTID,COMMENTS FROM CampusDev.CU_POLY WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
cmd.CommandText = "UPDATE CampusDev.CU_POLY SET PDF_Storage = :PDF_Storage WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
StringWriter SW = new StringWriter();
ds.WriteXml(SW);
cmd.Parameters.Add(":PDF_Storage", SW.ToString());
cmd.ExecuteNonQuery();
oracleConn.Close();
binddata();
}
protected void Deletedata(object s, GridViewDeleteEventArgs e)
{
binddata();
DataSet ds = gv.DataSource as DataSet;
ds.Tables[0].Rows[gv.Rows[e.RowIndex].DataItemIndex].Delete();
// ds.WriteXml(Server.MapPath("testxml.xml"));//Disabled now. Do database. Irfan. 07/09/10
String strConnect = GetConnString();
OracleConnection oracleConn = new OracleConnection();
oracleConn.ConnectionString = strConnect;
oracleConn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE CampusDev.CU_POLY SET PDF_Storage = :PDF_Storage WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
StringWriter SW = new StringWriter();
ds.WriteXml(SW,XmlWriteMode.IgnoreSchema);
Regex regex = new Regex(#"(\r\n|\r|\n)+");
string newText = regex.Replace(SW.ToString(), "");
cmd.Parameters.Add(":PDF_Storage", newText);
cmd.ExecuteNonQuery();
oracleConn.Close();
binddata();
string blah = "blah";
}
Here is how I have done this in the past. For the insert you can basically just write the dataset's xml representation out to a string and save it directly to a field in the database. In this case I leveraged Sql Server 2008 and an XML datatype for the database field. I think the datatype in Oracle is XMLTYPE.
Insert:
public static void InsertDataSet(string key, DataSet dataSet)
{
string xml = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
dataSet.WriteXml(ms, XmlWriteMode.WriteSchema);
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
xml = sr.ReadToEnd();
}
using (SqlServerConnection c = new SqlServerConnection(connectionString))
{
c.command.CommandType = CommandType.StoredProcedure;
c.command.CommandText = "some stored procedure to do the insert";
c.command.Parameters.Clear();
c.command.Parameters.Add(new SqlParameter("#key", key));
c.command.Parameters.Add(new SqlParameter("#xml", xml));
c.command.ExecuteNonQuery();
}
}
}
Getting the dataset back out of the database is as simple as reading the xml data from the database back into a TextReader and then building a new DataSet.
Get:
public static DataSet GetDataSet(string key)
{
using (SqlServerConnection c = new SqlServerConnection(connectionString))
{
c.command.CommandType = CommandType.StoredProcedure;
c.command.CommandText = "some stored procedure to get the xml";
c.command.Parameters.Clear();
c.command.Parameters.Add(new SqlParameter("#key", key));
dr = c.command.ExecuteReader();
if (dr == null)
{
return null;
}
if (dr.HasRows)
{
while (dr.Read())
{
if (dr["xml_field"] != DBNull.Value)
{
TextReader tr = new StringReader(dr["xml_field"].ToString());
result = new DataSet();
result.ReadXml(tr, XmlReadMode.ReadSchema);
}
}
}
}
return result;
}
Hope this helps.
Enjoy!

Resources