I want to convert .xlsx file to html using NPOI. Is this possible? I know , xls to html conversion is available using NPOI. But not sure if NPOI provide option to convert .xlsx file to html also. Thanks
You can use ExcelToHtmlConverter. It has method ProcessWorkbook which accepts IWorkbook as a parameter. So it can be used to convert either HSSFWorkbook (xls) or XSSFWorkbook (xlsx).
public void ConvertXlsxToHtml()
{
XSSFWorkbook xssfwb;
var fileName = #"c:\temp\test.xlsx";
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
xssfwb = new XSSFWorkbook(file);
ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter();
//set output parameter
excelToHtmlConverter.OutputColumnHeaders = false;
excelToHtmlConverter.OutputHiddenColumns = true;
excelToHtmlConverter.OutputHiddenRows = true;
excelToHtmlConverter.OutputLeadingSpacesAsNonBreaking = false;
excelToHtmlConverter.OutputRowNumbers = false;
excelToHtmlConverter.UseDivsToSpan = true;
//process the excel file
excelToHtmlConverter.ProcessWorkbook(xssfwb);
//output the html file
excelToHtmlConverter.Document.Save(Path.ChangeExtension(fileName, "html"));
}
}
Related
I save info from datagrid to xslx file located at the folder, after I want to download this file.
I have code, that is working correct, but in my project when I try to download file it return nothing. Maybe it because of protection or user role is admin.
I have tried with different folders, and I'm sure that folder is not a problem.
What else it can be?
public FileResult downloadFile(string filePath)
{
IFileProvider provider = new PhysicalFileProvider(filePath);
IFileInfo fileInfo = provider.GetFileInfo(fileName);
var readStream = fileInfo.CreateReadStream();
var mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
return File(readStream, mimeType, fileName);
}
I have try your code and everthing seems ok
public IActionResult Index()
{
var fileName = "SN-export.xlsx";
string filePath = _hostingEnvironment.WebRootPath;
string fileName2 = Path.Combine(filePath, fileName);
FileInfo excelFile = new FileInfo(fileName2);
if (excelFile.Exists) {
excelFile.Delete();
excelFile = new FileInfo(fileName2);
}
// excel.SaveAs(excelFile); Have to comment this because i don't know what excel nuget you are using
// For testing purpose i have used the following two lines
var file = System.IO.File.Create(excelFile.ToString());
file.Close();
return DownloadFile(filePath, fileName);
}
public FileResult DownloadFile(string filePath,string fileName)
{
IFileProvider provider = new PhysicalFileProvider(filePath);
IFileInfo fileInfo = provider.GetFileInfo(fileName);
var readStream = fileInfo.CreateReadStream();
var mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
return File(readStream, mimeType, fileName);
}
I'm trying to generate an excel file / stream in my web api and return it in a HttpResponseMessage to serve it to the client in Angular 5 as a download.
The generation succeeds and an xlsx file is generated and saved on the server, but when I return it in the Content of my httpResponseMessage, my browser shows just some json instead of the whole excel file.
{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Disposition","value":["attachment; filename=636742856488421817.xlsx"]},{"key":"Content-Type","value":["application/ms-excel"]},{"key":"Content-Length","value":["22780"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}
This is how I create the excel file and returns it:
var dataBytes = File.ReadAllBytes(fileName);
var dataStream = new MemoryStream(dataBytes);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/ms-excel");
httpResponseMessage.Content.Headers.ContentLength = dataStream.Length;
I solved this:
Here is what I did
Helper class which creates the excel package and converts it to a Stream
var fileName = DateTime.Now.Ticks + ".xlsx";
FileInfo file = new FileInfo(fileName);
FileInfo templateFile = new FileInfo(#"Templates/ReportTemplate.xlsx");
ExcelPackage package = new ExcelPackage(file, templateFile);
ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();
... filling rows and cells goed here ...
var dataBytes = package.GetAsByteArray();
Stream dataStream = new MemoryStream(dataBytes);
dataStream.Seek(0, SeekOrigin.Begin);
return dataStream;
In the controller I return the file to the Angular client like this:
var stream = _helperClass.GenerateReport(exportDate, exportTitle);
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"Report-{DateTime.Now.ToShortDateString()}.xlsx");
In the Angular component I do this after I receive the response:
var blob = new Blob([res], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
var blobURL = window.URL.createObjectURL(blob);
var anchor = document.createElement("a");
anchor.download = `Report-${new Date().toISOString()}.xlsx`;
anchor.href = blobURL;
anchor.click();
Try this following code:
For conroller:
[Route("DownLoadExcel")]
public IActionResult DownLoadExcel()
{
var pack = new ExcelPackage();
ExcelWorksheet worksheet = pack.Workbook.Worksheets.Add("sample");
//First add the headers
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
//Add values
worksheet.Cells["A2"].Value = 1000;
worksheet.Cells["B2"].Value = "Jon";
return File(pack.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Sample.xlsx");
}
For client side:
window.open("../.../DownLoadExcel");
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");
I use Apache POI and I have a lot of data that I want to write to *.xls file in parts.
Now I use:
FileOutputStream fileOutputStream = null;
File tmpFile = new File("blabla.xls");
Workbook workbook = null;
try {
for(int i = 1; i <= pageNumber; i++) {
workbook = xlsGenerator.generateWorkbook(someData, i);
fileOutputStream = new FileOutputStream(tmpFile);
workbook.write(fileOutputStream);
}
}
But it doesn't work. It always replace old data instead of appending new data to workbook. So, are there ways to write in parts?
I'm developing a rather simple visual WebPart for SharePoint Foundation Server 2010.
It's supposed to upload an image file to the SharePoint server and display it afterwards.
While I can successfully upload the file to a previously created document library, the file cannot be displayed (IE shows the red cross). When I upload an exact copy of the file using SharePoint frontend, it can be opened. I hope that someone can tell me what I'm missing.
Below you can find the code that successfully uploads a file to the server:
SPContext.Current.Web.AllowUnsafeUpdates = true;
string path = "";
string[] fileName = filePath.PostedFile.FileName.Split('\\');
int length = fileName.Length;
// get the name of file from path
string file = fileName[length - 1];
SPWeb web = SPContext.Current.Web;
SPFolderCollection folders = web.Folders;
SPFolder folder;
SPListCollection lists = web.Lists;
SPDocumentLibrary library;
SPList list = null;
Guid guid = Guid.Empty;
if (lists.Cast<SPList>().Any(l => string.Equals(l.Title, "SPUserAccountDetails-UserImages")))
{
list = lists["SPUserAccountDetails-UserImages"];
}
else
{
guid = lists.Add("SPUserAccountDetails-UserImages", "Enthält Mitarbeiter-Fotos", SPListTemplateType.DocumentLibrary);
list = web.Lists[guid];
}
library = (SPDocumentLibrary)list;
folder = library.RootFolder.SubFolders.Add("SPUserAccountDetails");
SPFileCollection files = folder.Files;
Stream fStream = filePath.PostedFile.InputStream;
byte[] MyData = new byte[fStream.Length];
Stream stream = new MemoryStream();
stream.Read(MyData, 0, (int)fStream.Length);
fStream.Close();
bool bolFileAdd = true;
for (int i = 0; i < files.Count; i++)
{
SPFile tempFile = files[i];
if (tempFile.Name == file)
{
folder.Files.Delete(file);
bolFileAdd = true;
break;
}
}
if (bolFileAdd)
{
SPFile f = files.Add(file, MyData);
f.Item["ContentTypeId"] = "image/jpeg";
f.Item["Title"] = file;
f.Item.SystemUpdate();
SPContext.Current.Web.AllowUnsafeUpdates = false;
imgPhoto.ImageUrl = (string)f.Item[SPBuiltInFieldId.EncodedAbsUrl];
}
Never mind. My code seems to mess with the file content. I'll post the solution later.
edit:
I'm stupid and sorry :-/
I replaced this:
Stream fStream = filePath.PostedFile.InputStream;
byte[] MyData = new byte[fStream.Length];
Stream stream = new MemoryStream();
stream.Read(MyData, 0, (int)fStream.Length);
fStream.Close();
with this:
Stream fStream = filePath.PostedFile.InputStream;
byte[] MyData = new byte[fStream.Length];
BinaryReader binaryReader = new BinaryReader(fStream);
MyData = binaryReader.ReadBytes((Int32)fStream.Length);
fStream.Close();
binaryReader.Close();
and suddenly it all worked ;-)