I am getting the following error:
, value hexadecimal 0x02, caracter not valid.
using this code:
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt1);
Response.Clear();
Response.Buffer = true;
Response.Charset ="";
Response.ContentType = "application/vnd.openxmlformats- officedocument.spreadsheetml.sheet";
//Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
I have tried different ways, but I still get the same error. "dt1" is filled from stored procedure.
to use ClosedXML I am currently doing the following and I call this method to open the Excel from a web page.
to call the ExportToExcel_SomeReport you would do it like this I create a public static class called Extensions
Extensions.ExportToXcel_SomeReport(dt1, fileName, this.Page);//Call the method on your button click
//this will be in the static public class you create
internal static void ExportToXcel_SomeReport(DataTable dt, string fileName, Page page)
{
var recCount = dt.Rows.Count;
fileName = string.Format(fileName, DateTime.Now.ToString("MMddyyyy_hhmmss"));
var xlsx = new XLWorkbook();
var ws = xlsx.Worksheets.Add("Some Custom Report");
ws.Style.Font.Bold = true;
ws.Cell("C5").Value = "Some Custom Header Report";
ws.Cell("C5").Style.Font.FontColor = XLColor.Black;
ws.Cell("C5").Style.Font.SetFontSize(16.0);
ws.Cell("E5").Value = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
ws.Range("C5:E5").Style.Font.SetFontSize(16.0);
ws.Cell("A7").Value = string.Format("{0} Records", recCount);
ws.Style.Font.Bold = false;
ws.Cell(9, 1).InsertTable(dt.AsEnumerable());
ws.Row(9).InsertRowsBelow(1);
// ws.Style.Font.FontColor = XLColor.Gray;
ws.Columns("1-8").AdjustToContents();
ws.Tables.Table(0).ShowAutoFilter = true;
ws.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
DynaGenExcelFile(fileName, page, xlsx);
}
private static void DynaGenExcelFile(string fileName, Page page, XLWorkbook xlsx)
{
page.Response.ClearContent();
page.Response.ClearHeaders();
page.Response.ContentType = "application/vnd.ms-excel";
page.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", fileName));
using (MemoryStream memoryStream = new MemoryStream())
{
xlsx.SaveAs(memoryStream);
memoryStream.WriteTo(page.Response.OutputStream);
memoryStream.Close();
}
page.Response.Flush();
page.Response.End();
}
Related
I'm getting this error in ExcelPackage.GetAsByteArray() while exporting excel. I have tried everything as UTF-8 encoding etc but nothing works.
Below is my code
public void function Export()
{
ExcelPackage package = ExportUtil.GetMacroEnabledExtract(ds, extractName, "Comments");
Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + ExportUtil.getFileName(extractName, ".xlsm") + "\"");
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
}
export function
public static ExcelPackage GetMacroEnabledExtract(DataSet ds, string extractName, string dataSheetName)
{
string appDataPath = HostingEnvironment.MapPath(#"~/App_Data");
string filePath = Path.Combine(appDataPath, "MacroTemplate.xlsm");
FileInfo templateFile = new FileInfo(filePath);
ExcelPackage package = new ExcelPackage(templateFile, false);
string fileName = getFileName(extractName, ".xlsm");
createDataWorkSheetMacroEnabled(package, ds.Tables[0], dataSheetName, templateFile); //Sheet 1
return package;
}
private static void createDataWorkSheetMacroEnabled(ExcelPackage package, DataTable table, string worksheetName, FileInfo file)
{
ExcelWorksheet wsData = package.Workbook.Worksheets[1];
wsData.Cells["A1"].LoadFromDataTable(table, true);
ExcelTextFormat format = new ExcelTextFormat();
format.Encoding = new UTF8Encoding();
wsData.Cells.LoadFromText(file, format);
}
I am working on export functionality using PDFsharp in .Net MVC I am not getting any error in my code but not getting PDF file in response.
I have tried doing it manually writing it to specific path with the help of : System.IO.File.WriteAllBytes(path1, bytes); and it's working perfectly, but I am not getting PDF in Response with the help of
Response.BinaryWrite(bytes);
Response.OutputStream.Write(bytes, 0, bytes.Length);
Anyone have faced this type of issue or someone from community please help
Here is my code :
public bool ExportPdf(string htmlcontenttbl)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=Myfile.pdf");
Response.ContentType = "application/pdf";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
PdfDocument document =
PdfGenerator.GeneratePdf(htmlcontenttbl.ToString(), PdfSharp.PageSize.A4,
30);
var config = new PdfGenerateConfig();
config.PageOrientation = PageOrientation.Landscape;
config.PageSize = PageSize.A4;
config.MarginBottom = 30;
config.MarginTop = 30;
byte[] bytes = null;
using (MemoryStream stream = new MemoryStream())
{
document.Save(stream, true);
bytes = stream.ToArray();
}
var path1 = Server.MapPath("~/Images/" +
DateTime.Now.TimeOfDay.Ticks + "result.pdf");
//System.IO.File.WriteAllBytes(path1, bytes);
//Response.BinaryWrite(bytes);
//Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.Flush();
Response.End();
return true;
}
thank you,
I am working on Export to PDF funtionality using C# and PDFSharp. I am getting this error:
Value cannot be null.
Parameter name: elementId
The error is on this line :
PdfDocument document = PdfGenerator.GeneratePdf(htmlcontenttbl.ToString(), PdfSharp.PageSize.A4, 30);
Here's the whole method:
public bool ExportPdf(string htmlcontenttbl)
{
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=Myfile.pdf");
//Response.AddHeader("Content-Disposition", "inline;filename=file.pdf");
//Response.AppendHeader("Content-Disposition", "attachment; filename=Myfile.pdf");
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
PdfDocument document = PdfGenerator.GeneratePdf(htmlcontenttbl.ToString(), PdfSharp.PageSize.A4, 30);
var config = new PdfGenerateConfig();
config.PageOrientation = PageOrientation.Landscape;
config.PageSize = PageSize.A4;
config.MarginBottom = 30;
config.MarginTop = 30;
//PdfDocument document = PdfGenerator.GeneratePdf(htmlcontenttbl, config);
byte[] bytes = null;
using (MemoryStream stream = new MemoryStream())
{
document.Save(stream, true);
bytes = stream.ToArray();
}
//var path1 = Server.MapPath("~/Images/" + DateTime.Now.TimeOfDay.Ticks + "result.pdf");
//System.IO.File.WriteAllBytes(path1, bytes);
//Response.TransmitFile(path1, 0, bytes.Length);
//Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
return true;
}
That exception can occur if you have a blank anchor tag.
It is likely ultimately being generated from here.
You should remove the blank anchor tag.
iv'e created a method to generate a pdf file from a form, it got saved to the correct path using itexsharp, but the problem is i can't download it.
this is my code :
private void FillForm(Dictionary<string, string> dic)
{
var pdfTemplate = HttpContext.Current.Server.MapPath("~/ress/GENE_15_04_2014.pdf"); //_pdfTemplet;
var newFile = _newFileName + "_" + Guid.NewGuid() + ".pdf";
_gNewFile = newFile.ToString();
var pdfReader = new PdfReader(System.IO.File.ReadAllBytes(pdfTemplate));
var pfileStream = new FileStream(string.Format(HttpContext.Current.Server.MapPath("~/ress/") + "{0}", newFile), FileMode.Create);
var pdfStamper = new PdfStamper(pdfReader, pfileStream);
var pdfFormFields = pdfStamper.AcroFields;
foreach (var entry in dic)
{
pdfFormFields.SetField(entry.Key, entry.Value);
}
pdfStamper.FormFlattening = true;
pdfStamper.JavaScript = "this.print(true);\r";
pdfStamper.Writer.CloseStream = false;
pdfReader.Close();
pdfStamper.Close();
UPContract.Update();
pfileStream.Close();
pdf.FilePath = string.Format("../Ress/{0}", Path.GetFileName(_gNewFile));
Response.Clear();
byte[] bytes = System.IO.File.ReadAllBytes(string.Format(HttpContext.Current.Server.MapPath("~/ress/") + "{0}", _gNewFile));
Response.ContentType = "application/pdf";
MemoryStream ms = new MemoryStream(bytes);
Response.AddHeader("content-disposition", "attachment;filename=" + "fiche abonnement_" + _gNewFile + ".pdf");
Response.Buffer = true;
ms.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
If you want to pass a file you can skip the byte array and MemoryStream and just use Response.WriteFile(string)
I use Web Forms. I try to convert ClosedXML excel workbook to pdf using Spire.XLS and download it by a client.
Here is my code:
protected void btnExport_OnClick(object sender, EventArgs e)
{
var excel = Reporting.GenerateExcel(); //custom, return XLWorkbook object
string myName = Server.UrlEncode(121 + "_" + DateTime.Now.ToShortDateString() + ".xlsx");
MemoryStream stream = GetStream(excel);
MemoryStream stream1 = new MemoryStream();
Workbook book = new Workbook();
book.LoadFromStream(stream);
book.SaveToStream(stream1, FileFormat.PDF);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + myName);
Response.ContentType = "application/pdf";
Response.BinaryWrite(stream1.ToArray());
Response.End();
}
public MemoryStream GetStream(XLWorkbook excelWorkbook)
{
MemoryStream fs = new MemoryStream();
excelWorkbook.SaveAs(fs);
fs.Position = 0;
return fs;
}
It seems like I receive not correct pdf. Thanks