Error While Export To Excel in sharepoint 2010 Programmatically - sharepoint

The file you are trying is in a different format than specified by the file extension.Verify that the file is not corrupted and is from a trusted source before opening the file.Do you want to open the file now?
and this 'export to excel' dead the events on the page.
Here is my code
public void ExportToExcelitems(DataTable dt, string fileNameWithoutExt)
{
if (dt.Rows.Count > 0)
{
string filename = fileNameWithoutExt + ".xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
var dgGrid = new GridView();
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.HeaderRow.BackColor = System.Drawing.Color.White;
dgGrid.HeaderRow.BackColor = System.Drawing.Color.White;
foreach (GridViewRow row in dgGrid.Rows)
{
row.BackColor = System.Drawing.Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = dgGrid.RowStyle.BackColor;
}
else
{
cell.BackColor = System.Drawing.Color.LightGray;
}
}
}
dgGrid.AutoGenerateColumns = false;
dgGrid.RenderControl(hw);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
}
}

I think you should consider using OpenXML (or more specfically ClosedXML) to build a modern Excel file with the xlsx extension.
Open XML SDK: https://learn.microsoft.com/en-us/office/open-xml/open-xml-sdk
Closed XML (nuget): https://www.nuget.org/packages/ClosedXML/
Code Samples: https://github.com/ClosedXML/ClosedXML/wiki/Deliver-an-Excel-file-in-ASP.NET

Related

Not able to read excel sheet saved as xls using closedxml

I have the below code to save the data in excel sheet as .xls
public ActionResult ExportToExcel()
{
DataTable tbl = CopyGenericToDataTable(res);
tbl.TableName = "InvalidInvoices";
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(tbl);
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename= "+fileName + ".xls");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
Above is code which download the xls excel sheet at client side. It works fine the data gets saved in excel sheet.
Problem is if I try to upload this same file using below code -
if (files != null)
{
HttpPostedFileBase upload = files.FirstOrDefault();
Stream stream = upload.InputStream;
DataSet result = new DataSet();
if (upload != null && upload.ContentLength > 0)
{
if (upload.FileName.EndsWith(".xls") || upload.FileName.EndsWith(".xlsx"))
{
// ExcelDataReader works with the binary Excel file, so it needs a FileStream
// to get started. This is how we avoid dependencies on ACE or Interop:
// We return the interface, so that
IExcelDataReader reader = null;
if (upload.FileName.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (upload.FileName.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
reader.IsFirstRowAsColumnNames = false;
result = reader.AsDataSet();
reader.Close();
}
}
}
In above code I am getting error in ExcelReaderFactory.CreateBinaryReader(stream);
In stream it has the values in bytes too just on using createBinaryreader of excelreaderfactory reader has error message as 'Invalid file signature'.
Any help will be highly appreciated.
ClosedXML generates .xlsx files, not .xls files.
Check your code:
Response.AddHeader("content-disposition", "attachment;filename= "+fileName + ".xls");

Exporting from GridView to Excel is not show Persian correctly

Bind the GridView by SqlDataSource and I wrote below code to export from GridView to Excel:
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
gvReportPrint.GridLines = GridLines.Both;
gvReportPrint.Font.Name = "'BYekan'";
foreach (GridViewRow row in gvReportPrint.Rows)
{
row.Cells[2].Attributes.Add("class", "textmode");
}
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
gvReportPrint.HeaderStyle.Font.Bold = true;
Response.Write(style);
gvReportPrint.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.End();
During Export From GridView to Excel, unicode characters don't show correctly,
they are shown like this:
--> Click this link to show the problem <--
It seems that you are using asp:GridView,I had the same issue and using GridView class solved it like below :
public void ToExcel(DataTable dt, string reportName)
{
if (dt.Rows.Count > 0)
{
string filename = string.Format("{0}.xls", reportName);
GridView gv = new GridView();
gv.DataSource = dt;
gv.HeaderStyle.BackColor = System.Drawing.Color.FromArgb(0, 119, 179);
gv.HeaderStyle.ForeColor = System.Drawing.Color.FromArgb(250, 250, 250);
gv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromArgb(191, 191, 191);
gv.Font.Name = "Tahoma";
gv.Font.Size = 10;
gv.DataBind();
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
gv.RenderControl(hw);
HttpContext.Current.Response.Output.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
and dt should be your data source for gridview.
Also please take a look at ASP.NET Excel export encoding problem

Exporting from gridview to excel is not showing long numbers

Hello I'm trying to export my data from a gridview to excel the problem is I have a nvarchar column the have the following barcode: 00373228210001695726 and in excel after export it looks like this 3,73228E+17
my query looks like this:
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=AP;Initial Catalog=MGW;User Id=sa;Password=GaUbdFO2;App=EntityFramework;");
try
{
connection.Open();
string sqlStatement = " ";
sqlStatement += " SELECT UserName AS UserID, Site, AddressID, Parameters, Content AS Barcode , TriggerDate, ReceivedDate, Action, DeviceID, Longitude, Latitude, CASE WHEN Latitude != '' THEN 'View Map Location' Else 'No Location' END AS LatitudeMSG FROM RequestWithLocation WHERE";
sqlStatement += " Content = #Content ";
if (!string.IsNullOrWhiteSpace(TextBoxStart.Text) && !string.IsNullOrWhiteSpace(TextBoxEnd.Text))
{
sqlStatement += " AND TriggerDate >= #TriggerDateStart AND TriggerDate <= #TriggerDateEnd ";
}
sqlStatement += " ORDER BY TriggerDate DESC";
using (SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection))
{
sqlCmd.Parameters.AddWithValue("#Content", TextBoxSearch.Text);
if (!string.IsNullOrWhiteSpace(TextBoxStart.Text) && !string.IsNullOrWhiteSpace(TextBoxEnd.Text))
{
sqlCmd.Parameters.AddWithValue("#TriggerDateStart", Convert.ToDateTime(TextBoxStart.Text));
sqlCmd.Parameters.AddWithValue("#TriggerDateEnd", Convert.ToDateTime(TextBoxEnd.Text).AddDays(+1));
}
using (SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
GridDisplayData.DataSource = dt;
GridDisplayData.DataBind();
lblError.Text = "";
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('No data found');", true);
}
}
}
}
catch (Exception)
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Search timed-out! try again..');", true);
}
EXPORT FUNCTION
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachchment; filename=Report_EventScan.xls; IMEX=1;");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridDisplayData.RenderControl(hw);
//Panel7.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
}
Use Response.Write("'" + sw.ToString()); to force a prefixed single quotation character in front of the number. That forces Excel to adopt text formatting.
(I'm assuming that + is a string concatenation in your language; it might be &).
I solved my problem. this is what I did:
You can download the EPPlus Excel reader from here http://epplus.codeplex.com/
Then using OfficeOpenXml; on top of your project and the following code to your export button, this should work for everyone who use a DataSet which is saved in a ViewState
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
DataSet dt = new DataSet();
dt = (DataSet)ViewState["QueryTable"];
MemoryStream ms = new MemoryStream();
int i = 1;
using (ExcelPackage package = new ExcelPackage(ms))
{
foreach (DataTable table in dt.Tables)
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("My Excel Report " + i++);
worksheet.Cells["A1"].LoadFromDataTable(table, true);
}
Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachchment; filename= test.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
Response.End();
}
}

How to add download option for openwith and saveAs on exporting file to excel in servlet

Hii Guys !!!
I made an application in which i need to export data from database into .excel formate in which i have given hard coded path for generated .excel file to save at particular position on the system.Now as per my requirement I need to give download option for openwith and saveAs from the browser.
Below I am postion my code .Plz guys help me ...will be gratefull.Thanx in advance...
String datum1 = request.getParameter("fromdate");
String datum2 = request.getParameter("todate");
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdfSource.parse(datum1);
Date date2 = sdfSource.parse(datum2);
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
datum1 = sdfDestination.format(date);
System.out.println(datum1);
datum2 = sdfDestination.format(date2);
System.out.println(datum2);
String filename = "d:/".concat(datum1).concat(" ").concat("To").concat(" ").concat(datum2).concat(".xls");
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("CallBillingSystem");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("calldate");
rowhead.createCell((short) 1).setCellValue("src");
rowhead.createCell((short) 2).setCellValue("dst");
String strQuery = "";
ResultSet rs = null;
conexion conexiondb = new conexion();
conexiondb.Conectar();
strQuery = "SELECT * FROM cdrcost where date(calldate) between '" + datum1 + "' and '" + datum2 + "'";
// strQuery = "SELECT * FROM cdrcost where date(calldate) between '2011-09-01' and '2012-01-01'";
rs = conexiondb.Consulta(strQuery);
int i = 1;
while (rs.next()) {
HSSFRow row = sheet.createRow((short) i);
row.createCell((short) 0).setCellValue(rs.getString("calldate"));
row.createCell((short) 1).setCellValue(rs.getString("src"));
row.createCell((short) 2).setCellValue(rs.getString("dst"));
i++;
}
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
} catch (Exception ex) {
System.out.println(ex);
}
}
You should use Content-Disposition in the response header
Try using this code
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=FileName.xls");
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();

error occured when uploading a file with IIS

I have developed a web application, which runs good when executed from Visual studio.
The theme of the application is to get the content in the excel file and display it.
We had a file upload control in our application, to get the excel file.
It works like charm when executed from the VS and i could see the desired result, but it is giving error when browsed through IIS.
Code is developed in Framework 4.0
The excel file is not uploading, and throws an error that error occured while reading the file.
Here is my code ..
Can you detect what goes wrong when browsed through IIS ?
DataSet dsRates = new Schemas.Rates();
DataTable dtExcel = new DataTable();
dtDBTable = dsRates.Tables[0];
DataTable dtColumnNameNotFound = new DataTable();
FileStream stream;
string changed = string.Empty;
string FilePath = string.Empty;
try
{
if (ValidateUserInputs())
{
DataSet dsExcel = new DataSet();
OleDbConnection con = new OleDbConnection();
try
{
if (fupExtract.HasFile == true)
{
FilePath = Server.MapPath("~/Temp/" + fupExtract.PostedFile.FileName);
fupExtract.SaveAs(FilePath);
}
else
{
fupExtract = ((FileUpload)Session["FileUploadCtrl"]);
FilePath = Server.MapPath("~/Temp/" + fupExtract.PostedFile.FileName);
fupExtract.SaveAs(FilePath);
}
//Read the Excel Data in to Datatable
string _ConnectionString = string.Empty;
string _Extension = Path.GetExtension(FilePath);
if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + FilePath + ";Extended Properties=" + (char)34 + "Excel 8.0;HDR=NO;IMEX=1;" + (char)34;
}
//Use ACE OleDb
else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=" + (char)34 + "Excel 8.0;HDR=NO;IMEX=1;" + (char)34;
}
else
{
lblMessage.Text = fupExtract.FileName + "is not a supported format, only '.xls|.xlsx' files are supported";
return;
}
int i = 0;
con = new OleDbConnection(_ConnectionString);
con.ResetState();
con.Open();
DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow Sheet in dt.Rows)
{
OleDbDataAdapter daExcel = new OleDbDataAdapter("SELECT * FROM [" + Sheet["TABLE_NAME"].ToString().Trim() + "]", con);
DataTable dtData = new DataTable();
daExcel.Fill(dtData);
var filteredRows = dtData.Rows.Cast<DataRow>().Where(row => row.ItemArray.Any(field => !(field is System.DBNull)));
if (filteredRows.Count() > 0)
{
dsExcel.Tables.Add(dtData);
}
i++;
}
con.Close();
}
catch (Exception ex)
{
lblMessage.Text = "Error occured while reading the file";
con.Close();
}
finally
{
if (File.Exists(FilePath))
{
File.Delete(FilePath);
}
}
Please help
Thanks,
Tou can use Interop in order to read your excel document
object misValue = System.Reflection.Missing.Value;
var xlApp = new Excel.ApplicationClass();
var xlWorkBook = xlApp.Workbooks.Open("yourFile.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
var xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Console.Write(xlWorkSheet.get_Range("A1","A1").Value2.ToString());
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
I've got the answer to my question.
It's that I haven't installed Office 64-bit and Microsoft.ACE.OLEDB.12.0. The one I'm using is 32-bit.

Resources