I want to export data from data table to Excel file. I need to save the file on server. I am using the console application for this project.
Since you haven't mentioned if excel is installed, i recommend EPPlus to create the excel file. It has a convenient method LoadFromDataTable:
using (var pck = new ExcelPackage())
{
var ws = pck.Workbook.Worksheets.Add("Worksheet-Name");
ws.Cells["A1"].LoadFromDataTable(dataTable1, true, OfficeOpenXml.Table.TableStyles.Medium1);
using(var fileStream = File.Create(path))
pck.SaveAs(fileStream);
}
Edit i've only just seen that you have tagged export-to-csv.
var lines = dataTable1.AsEnumerable()
.Select(r => string.Join(",", r.ItemArray));
string csv = string.Join(Environment.NewLine, lines);
File.AppendAllText(path, csv);
if (DtReqDetails != null)
{
string attachment = "attachment; filename=History.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in DtReqDetails.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in DtReqDetails.Rows)
{
tab = "";
for (i = 0; i < DtReqDetails.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
If you are using MS SQL, then they have a built-in procedure for exporting a table to an Excel spreadsheet. No coding required.
Related
I am exporting data in to excel using open xml sdk. Now i want that data directly export using data table not by using grid view when i give data table directly into wb.Worksheets.Add(dt) it give worksheets name exception,secondly i want to save file into some location rather than downloading my code is below.
DataTable dt = new DataTable("GridView_Data");
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView1.Rows)
{
dt.Rows.Add();
for (int i = 0; i < row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
}
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
I have GridView in my web application, while click the Export button the value from gridview to be export into new sheet in existing excel file accordingly as Day1, Day2, ...
Thanks!!!
You can use EPPlus Library for this, here's a quick snippet on how to create sheets:
string filePath = "~/App_Data/emptyExcelFile.xlsx";
FileInfo fi = new FileInfo(Server.MapPath(filePath));
using (ExcelPackage xlPackage = new ExcelPackage(fi))
{
for (int i = 1; i <= 3; i++)
{
ExcelWorksheet worksheet;
worksheet = xlPackage.Workbook.Worksheets.Add("Day"+i, sheetName);
}
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + "myExcelFile.xlsx");
Response.BinaryWrite(xlPackage.GetAsByteArray());
Response.Flush();
Response.End();
}
Hope this helps.
Im having some trouble finding a way to Upload a document to the database in varbinary(max) with ASP.Net Webpages 2 and I would also like to download it.
So far what i have is this below which supposed to upload a file to a directory on the website but it isn't doing anything. Any help would be great. Thanks
var fileName = "";
var fileSavePath = "";
int numFiles = Request.Files.Count;
int uploadedCount = 0;
for (int i = 0; i < numFiles; i++)
{
var uploadedFile = Request.Files[i];
if (uploadedFile.ContentLength > 0)
{
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/UploadedFiles/" +
fileName);
uploadedFile.SaveAs(fileSavePath);
uploadedCount++;
}
}
message = "File upload complete. Total files uploaded: " +
uploadedCount.ToString();
The following code goes at the top of the page where you have your file upload. Note that you should amend the table and field names according to your database. Also, you should ensure that the form that includes your upload control has the enctype attribute set to multipart/form-data:
#{
int id = 0;
var fileName = "";
var fileMime = "";
if (IsPost) {
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
if(fileName != String.Empty)
{
fileMime = uploadedFile.ContentType;
var fileStream = uploadedFile.InputStream;
var fileLength = uploadedFile.ContentLength;
byte[] fileContent = new byte[fileLength];
fileStream.Read(fileContent, 0, fileLength);
var db = Database.Open("FileUploading");
var sql = "INSERT INTO Files (FileName, FileContent, MimeType) VALUES (#0,#1,#2)";
db.Execute(sql, fileName, fileContent, fileMime);
}
}
}
To display a file from the database, you need a separate "handler" file that contains just this code:
#{
int id = 0;
if(Request["Id"].IsInt()){
id = Request["Id"].AsInt();
var db = Database.Open("FileUploading");
var sql = "Select * From Files Where FileId = #0";
var file = db.QuerySingle(sql, id);
if(file.MimeType.StartsWith("image/")){
Response.AddHeader("content-disposition", "inline; filename=" + file.FileName);
} else {
Response.AddHeader("content-disposition", "attachment; filename=" + file.FileName);
}
Response.ContentType = file.MimeType;
Response.BinaryWrite((byte[])file.FileContent);
}
}
This file is used as the src attribute for an image file or as the URL for a link to a file that should be downloaded such as a PDF or Word file. If you call this handler file "download.cshtml", the link for an image file saved in the database should look like this:
<img src="download.cshtml?Id=#id" alt="" />
where the Id parameter value is the id fo the file in the database. A download link looks like this:
Click Here
All of this has been taken from my article: http://www.mikesdotnetting.com/Article/148/Save-And-Retrieve-Files-From-a-Sql-Server-CE-Database-with-WebMatrix. The only difference between the article which features a SQL Compact database is that the data type for files in SQL CE is image as opposed to varbinary(max) in SQL Server.
based on your code..you are not uploading the image to the database. instead u're saving the image on your folder which is located in your root / UploadedFiles
to store the image in the database..you should use this code..
using (Stream fs = uploadedFile.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string contentType = uploadedFile.PostedFile.ContentType;
SqlParameter[] arParams = new SqlParameter[2];
arParams[0] = new SqlParameter("#ID", SqlDbType.Int);
arParams[0].Value = 1; 'example
arParams[1] = new SqlParameter("#contentType", SqlDbType.Varchar(50));
arParams[1].Value = contentType;
arParams[2] = new SqlParameter("#document", SqlDbType.Varbinary(MAX));
arParams[2].Value = bytes;
SqlHelper.ExecuteNonQuery(SQLConn, CommandType.StoredProcedure, "Upload_Attachment", arParams);
}
}
I need to download the excel to the specific folder
Example : D:\email
Now i was able to download the excel file in downloads ....but i need to download in D:\email
this is my code to create excel file :
protected void UploadDataTableToExcel(DataTable dtRecords)
{
string XlsPath = Server.MapPath(#"~/Add_data/test.xls");
string attachment = string.Empty;
if (XlsPath.IndexOf("\\") != -1)
{
string[] strFileName = XlsPath.Split(new char[] { '\\' });
attachment = "attachment; filename=" + strFileName[strFileName.Length - 1];
}
else
attachment = "attachment; filename=" + XlsPath;
try
{
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = string.Empty;
foreach (DataColumn datacol in dtRecords.Columns)
{
Response.Write(tab + datacol.ColumnName);
tab = "\t";
}
Response.Write("\n");
foreach (DataRow dr in dtRecords.Rows)
{
tab = "";
for (int j = 0; j < dtRecords.Columns.Count; j++)
{
Response.Write(tab + Convert.ToString(dr[j]));
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
catch (Exception ex)
{
//Response.Write(ex.Message);
}
}
you can manually move the file after download using
string sourceFile = #"C:\Users\test\Documents\Downloads\test.xls";
string destinationFile = #"D:\emails\test.xls";
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);
I'm using the below code and I'm specifying what type of application it is. However, when prompted to open the application the browser does not know what type of file it is. How can I make the browser already want to open it as an excel?
Any help is appreciated
public static void ExportToSpreadsheet(DataTable table, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in table.Columns)
{
context.Response.Write(column.ColumnName + "\t");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
context.Response.Write(row[i].ToString() + "\t");
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "application/ms-excel";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name+ ".xls");
context.Response.End();
}
try:
Response.ContentType = "application/vnd.ms-excel";
or for xlsx
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";