bulk data export to excel and download in ashx file - asp.net

I have an asp.net application in which I have a js file and an ashx file. Here in a download button click Im calling handler file in ajax call and retrieving sql table data in a json formatted string/data table and Im trying to export json formated string/data table to excel/csv file and download it. Please help me to find a solution. (Need a solution which help to export large amount of data and download)
I tried the below code but its not downloading excel file.
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
context.Response.ContentType = "application/csv";
HttpResponse response = context.Response;
string exportContent = ExportToSpreadsheet(JsonStringToDataTable(GetDataFromTable()),'excelfilename');
response.Write(exportContent);
context.Response.End();
}
public DataTable JsonStringToDataTable(string jsonString)
{
DataTable dt = new DataTable();
string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
List<string> ColumnsName = new List<string>();
foreach (string jSA in jsonStringArray)
{
string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
foreach (string ColumnsNameData in jsonStringData)
{
try
{
int idx = ColumnsNameData.IndexOf(":");
string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
if (!ColumnsName.Contains(ColumnsNameString))
{
ColumnsName.Add(ColumnsNameString);
}
}
catch (Exception ex)
{
//throw new Exception(string.Format(ex.Message + "Error Parsing Column Name : {0}", ColumnsNameData));
throw ex;
}
}
break;
}
foreach (string AddColumnName in ColumnsName)
{
dt.Columns.Add(AddColumnName);
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
nr[RowColumns] = RowDataString;
}
catch (Exception ex)
{
continue;
}
}
dt.Rows.Add(nr);
}
return dt;
}
private static string GetDataFromTable()
{
string returnValue = string.Empty;
var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
try
{
var result = //get data from sql table;
returnValue = serializer.Serialize(result);
}
catch (Exception e)
{
returnValue = serializer.Serialize(e.Message);
}
return returnValue;
}
public string ExportToSpreadsheet(DataTable table, string name)
{
string res = string.Empty;
try
{
//var resp = Response;
System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response;
resp.Clear();
if (table != null)
{
foreach (DataColumn column in table.Columns)
{
resp.Write(column.ColumnName + ",");
}
}
resp.Write(Environment.NewLine);
if (table != null)
{
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
resp.Write(row[i].ToString().Replace(",", string.Empty) + ",");
}
resp.Write(Environment.NewLine);
}
}
res = "successfully downloaded";
resp.ContentType = "text/csv";
resp.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
// resp.End();
}
catch(Exception ex)
{
res = ex.Message;
}
return res;
}

Start using a specialized libary like EPPlus. It will create real Excel files.
private void exportToExcel(DataTable dataTable)
{
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create the worksheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
//load the datatable into the sheet, with headers
worksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
//send the file to the browser
byte[] bin = excelPackage.GetAsByteArray();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-length", bin.Length.ToString());
Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\"");
Response.OutputStream.Write(bin, 0, bin.Length);
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}

Related

export excel cannot be open .xlsx

I am using asp.net C#, currently doing export excel file. I wish to export in .xlsx. everything seems fine until I open it. The code below is my code for export.
DataTable dt = GetData(sqlcommand);
if(dt.Rows.Count >0){
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=InventoryReport.xlsx");
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
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>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
The image below is the error I got after open the .xlsx file.
I hope someone could help on my work. Thanks!! really appreciate if yo could help me on this.. much appreciate!
use my code
using OfficeOpenXml;
using System.Data;
namespace Managed_Leverage_BAL
{
public static class ExcelExportHelper
{
public static void CreateExcelFromDataSet(this DataSet dsReportData, string strFileNameWithPath, int[] DateFormatColumnNumbers = null)
{
if (File.Exists(strFileNameWithPath)) File.Delete(strFileNameWithPath);
FileInfo newFile = new FileInfo(strFileNameWithPath);
using (ExcelPackage pck = new ExcelPackage(newFile))
{
for (int tableIndex = 0; tableIndex < dsReportData.Tables.Count; tableIndex++)
{
DataTable tbl;
tbl = dsReportData.Tables[tableIndex];
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(dsReportData.Tables[tableIndex].TableName);
ws.Cells["A1"].LoadFromDataTable(tbl, true);
if (tableIndex == 0)
for (int i = 0; i < DateFormatColumnNumbers.Count(); i++)
{
using (ExcelRange col = ws.Cells[DateFormatColumnNumbers[i], 1, DateFormatColumnNumbers[i] + tbl.Rows.Count, 1])
{
col.Style.Numberformat.Format = "dd-MMM-yyyy";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
}
string endHeader = "A";
for (int i = 0; i < tbl.Columns.Count - 1; i++)
{
endHeader = IncrementAlphabeticCounter(endHeader);
}
using (ExcelRange rng = ws.Cells["A1:" + endHeader + "1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); //Set color to dark blue
rng.Style.Font.Color.SetColor(Color.White);
}
}
pck.Save();
}
}
public static char[] CheckZ(char[] cCounter, int iPos)
{
if (iPos >= 0)
{
if (cCounter[iPos] >= 'Z')
{
cCounter[iPos] = 'A';
if (iPos == 0)
{
char[] array = new char[cCounter.Length + 1];
cCounter.CopyTo(array, 1);
cCounter = array;
cCounter[0] = 'A';
return cCounter;
}
cCounter = CheckZ(cCounter, iPos - 1);
return cCounter;
}
cCounter[iPos] = (char)(cCounter[iPos] + '\x0001');
}
return cCounter;
}
public static string IncrementAlphabeticCounter(string sCounter)
{
if (sCounter == "")
{
return sCounter;
}
char[] cCounter = sCounter.ToCharArray();
return new string(CheckZ(cCounter, cCounter.Length - 1));
}
}
in page
private void Download(DataSet ds)
{
String strPath = Server.MapPath("~/Docs/") + "your path";
ds.CreateExcelFromDataSet(strPath);
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=your file name.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.TransmitFile(strPath);
Response.Flush();
Response.End();
}
you will need epplus dll,get it here
http://download-codeplex.sec.s-msft.com/Download/Release?ProjectName=epplus&DownloadId=813458&FileTime=130743526623500000&Build=21028

how to display a .docx file in ckeditor?

I am making a website in ASP.NET using C#. I have stored .docx file in database in binary form. I have successfully retrieved it but now my task is that I have to open .docx file from database in ckeditor. And if I make any changes then the file in the database should be updated.
Code for saving .docx file in DB...
private Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data)" +
" values (#Name, #ContentType, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value
= contenttype;
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." +
" Upload Image/Word/PDF/Excel formats";
}
}
Retrieving from DB...
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
private void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
protected void btnshow_Click(object sender, EventArgs e)
{
string s1 = proclist.SelectedItem.Value;
string str1 = "";
db.con.Open();
try
{
string str = "select Name, ContentType, Data from tblFiles where Name='" + proclist.SelectedItem.Value + "'";
db.com = new SqlCommand(str, db.con);
SqlDataReader dr = db.com.ExecuteReader();
DataTable dt = GetData(db.com);
if (dt != null)
{
download(dt);
}
}
catch (NullReferenceException ex)
{
ex.ToString();
}
db.con.Close();
}
Javascript method:
function button_convertDocxToHTML_DisplayInCKEditor() {
$.ajax({
type: "POST",
async: false,
url: "Page.aspx/GetHTML",
data: "{'pathFile':'UploadFolder/',
'fileName':'docName',
'extensionFile':'.docx'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var resultHtml = result.d;
var objEditor = CKEDITOR.instances["yourID_Description"];
objEditor.setData(resultHtml);
},
error: function (result) {
// Unexpected error...
return false;
}
});
}
In the code-behind Page.aspx.cs, we have a web method in the side server. Maybe you will need some using like these:
using System.Reflection;
using System.Runtime.InteropServices;
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetHTML(string pathFile, string fileName, string extensionFile)
{
string result = string.Empty;
object path_DocsName = HttpContext.Current.Request.MapPath(pathFile + fileName + extensionFile);
object o = Missing.Value;
object oFalse = false;
object oTrue = true;
Microsoft.Office.Interop.Word._Application app = null;
Microsoft.Office.Interop.Word.Documents docs = null;
Microsoft.Office.Interop.Word.Document doc = null;
StreamReader reader = null;
try
{
app = new Microsoft.Office.Interop.Word.Application
{
Visible = false,
DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone
};
docs = app.Documents;
doc = docs.Open(ref path_DocsName, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
doc.Activate();
string newHtmlFile = HttpContext.Current.Request.MapPath("pathHtmlTEMPORAL/" + fileName + ".html");
// Create html file
doc.SaveAs(FileName: newHtmlFile, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML);
doc.Close(ref o, ref o, ref o);
app.Quit(ref o, ref o, ref o);
using (reader = new StreamReader(newHtmlFile, Encoding.GetEncoding("utf-8")))
{
result += reader.ReadToEnd();
reader.Dispose();
reader.Close();
}
}
catch (Exception ex)
{
result = Resources.WholeSite.Validation_UnexpectedError + ": " + ex.Message;
}
finally
{
if (doc != null) Marshal.FinalReleaseComObject(doc);
if (docs != null) Marshal.FinalReleaseComObject(docs);
if (app != null) Marshal.FinalReleaseComObject(app);
if (reader != null) { reader.Dispose(); reader.Close(); }
}
return result; // this result has all html that you have to display into CKEditor.
}

read from excel file to datatable asp.net

I got this code to read from a excel file after uploading
public static DataTable getDataTableFromExcel(string path)
{
using (var pck = new OfficeOpenXml.ExcelPackage())
{
using (var stream = File.OpenRead(path))
{
pck.Load(stream);
}
var ws = pck.Workbook.Worksheets.First();
DataTable tbl = new DataTable();
bool hasHeader = true; // adjust it accordingly( i've mentioned that this is a simple approach)
foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
{
tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
}
var startRow = hasHeader ? 2 : 1;
for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
{
var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
var row = tbl.NewRow();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
tbl.Rows.Add(row);
}
return tbl;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/Uploader/") + filename);
err.Text = "Upload status: File uploaded!";
DataTable dt = getDataTableFromExcel(Server.MapPath("~/Uploader/") + filename);
GridView1.DataSource = dt;
GridView1.DataBind();
err.Text = dt.Rows[1].ToString();
}
catch (Exception ex)
{
err.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
but i cannot understand it well ... if you could give me a little description about it ?
and how to read specific column
I need to read just the first and third and fifth column not all ... how to do that ?

Error reading words in the text file

I have been working on a code snippet today . A part of the Code reads the number of words in the file.I am using StreamReader to do the same , but it seems to give DirectoryNotFound Exception.Here is the code for the event
protected void Button1_Click(object sender, EventArgs e)
{
string filename = string.Empty;
string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
if (FileUpload1.HasFile)
{
string[] Exe = { ".txt" };
string FileExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
bool isValidFile = Exe.Contains(FileExt);
if (isValidFile)
{
int FileSize = FileUpload1.PostedFile.ContentLength;
if (FileSize <= 102400)
{
filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath(FilePath) + filename);
StreamReader sr = new StreamReader(FilePath+filename);
//The error shows up here and i have tried to use FilePath as the single parameter too
int counter = 0;
string delim = " ,.?!";
string[] fields = null;
string line = null;
while (!sr.EndOfStream)
{
line = sr.ReadLine();//each time you read a line you should split it into the words
line.Trim();
fields = line.Split(delim.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
counter += fields.Length; //and just add how many of them there is
}
sr.Close();
lblcount.Text = counter.ToString();
lblMsg.Text = "File upload successfully!";
}
else
{
lblMsg.Text = "File Size allowed upto 100kb!";
}
}
else
{
lblMsg.Text = "Please Upload a text File!";
}
}
else
{
lblMsg.Text = "Please upload a file!";
}
}
}
Can this be sorted out ??
Thanks in Advance!
Use Path.Combine to build paths:
string path = Path.Combine(Server.MapPath(FilePath), filename);
FileUpload1.SaveAs(path);
using(StreamReader sr = new StreamReader(path))
{
// ...
}

Large text reading in asp.net

This is my asp.net code behind:
public string ReadJSON(string jsonPath)
{
FileStream fs = new FileStream(jsonPath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string WillReturn = "";
try
{
WillReturn = sr.ReadToEnd();
return WillReturn;
}
catch (Exception ex)
{
WillReturn = null;
return WillReturn;
}
finally { sr.Close(); fs.Dispose(); }
}
But my data is 128 mb. And I am not taking error but no read.
I tried to debuging. WillReturn = sr.ReadToEnd(); context is: WillReturn could not evaluate expression.
How can I read to this?
It can read 127Mb text file into rows in 2 minutes 30++ seconds. Try this sample code
strFileName = ViewState("Physical path");
StreamReader sr = new StreamReader(strFileName);
do {
line = sr.ReadLine();
if ((line != null)) {
result = line.Split(Convert.ToChar(Constants.vbTab));
icount += 1;
dr = ds1.Tables(0).NewRow;
dr.BeginEdit();
dr("Item1") = result(0);
ds1.Tables(0).Rows.Add(dr);
}
} while (!(line == null));

Resources