i am new C# Beginner,
I created a function to generate Excel using ClosedXML.Excel, but i also want to zip the excel fill, how to zip excel file using Sharpziplib? anybody could give an adivse?thanks
public FileResult Export()
{
DataTable test = new DataTable("test");
test.Columns.AddRange(new DataColumn[] {new DataColumn("Name")});
foreach (var record in recordtest)
{
test.Rows.Add(record.name);
}
using (XLWorkbook ts = new XLWorkbook())
{
var testSheet = ts.Worksheets.Add(test);
testSheet.Cell("D4").Value = "First Name";
testSheet.Range("A4:A5").Merge();
testSheet.Range("A4:Q5").Columns().Style.Fill.BackgroundColor =
XLColor.Almond;
}
using (MemoryStream steam = new MemoryStream())
{
wb.SaveAs(steam);
var fileName = String.Format("{0}-{1}.xlsx", "test",
DateTime.Now.ToString("yyyyMMdd"));
return File(steam.ToArray(), "application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet", fileName);
}
}
If you want create zip, there are same way with CreateZipFile following this articles
https://github.com/icsharpcode/SharpZipLib/tree/master/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile
https://ourcodeworld.com/articles/read/629/how-to-create-and-extract-zip-files-compress-and-decompress-zip-with-sharpziplib-with-csharp-in-winforms
Related
I created a function to generate Excel using ClosedXML.Excel.it is working when i generate one Excel. Now, i would like to generate double excel in same function but not work. anybody could give an adivse?thanks
public FileResult Export()
{
DataTable test = new DataTable("test");
test.Columns.AddRange(new DataColumn[] {new DataColumn("Name")});
foreach (var record in recordtest)
{
test.Rows.Add(record.name);
}
using (XLWorkbook ts = new XLWorkbook())
{
var testSheet = ts.Worksheets.Add(test);
testSheet.Cell("D4").Value = "First Name";
testSheet.Range("A4:A5").Merge();
testSheet.Range("A4:Q5").Columns().Style.Fill.BackgroundColor =
XLColor.Almond;
}
using (MemoryStream steam = new MemoryStream())
{
wb.SaveAs(steam);
var fileName = String.Format("{0}-{1}.xlsx", "test",
DateTime.Now.ToString("yyyyMMdd"));
return File(steam.ToArray(), "application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet", fileName);
}
}
I am trying to create a process in .NET to convert a PDF and all it's pages + attachments to PNGs. I am evaluating libraries and came across PDFiumSharp but it is not working for me. Here is my code:
string Inputfile = "input.pdf";
string OutputFolder = "Output";
string fileName = Path.GetFileNameWithoutExtension(Inputfile);
using (PdfDocument doc = new PdfDocument(Inputfile))
{
for (int i = 0; i < doc.Pages.Count; i++)
{
var page = doc.Pages[i];
using (var bitmap = new PDFiumBitmap((int)page.Width, (int)page.Height, false))
{
page.Render(bitmap);
var targetFile = Path.Combine(OutputFolder, fileName + "_" + i + ".png");
bitmap.Save(targetFile);
}
}
}
When I run this code, I get this exception:
screenshot of exception
Does anyone know how to fix this? Also does PDFiumSharp support extracting PDF attachments? If not, does anyone have any other ideas on how to achieve my goal?
PDFium does not look like it supports extracting PDF attachments. If you want to achieve your goal, then you can take a look at another library that supports both extracting PDF attachments as well as converting PDFs to PNGs.
I am an employee of the LEADTOOLS PDF SDK which you can try out via these 2 nuget packages:
https://www.nuget.org/packages/Leadtools.Pdf/
https://www.nuget.org/packages/Leadtools.Document.Sdk/
Here is some code that will convert a PDF + all attachments in the PDF to separate PNGs in an output directory:
SetLicense();
cache = new FileCache { CacheDirectory = "cache" };
List<LEADDocument> documents = new List<LEADDocument>();
if (!Directory.Exists(OutputDir))
Directory.CreateDirectory(OutputDir);
using var document = DocumentFactory.LoadFromFile("attachments.pdf", new LoadDocumentOptions { Cache = cache, LoadAttachmentsMode = DocumentLoadAttachmentsMode.AsAttachments });
if (document.Pages.Count > 0)
documents.Add(document);
foreach (var attachment in document.Attachments)
documents.Add(document.LoadDocumentAttachment(new LoadAttachmentOptions { AttachmentNumber = attachment.AttachmentNumber }));
ConvertDocuments(documents, RasterImageFormat.Png);
And the ConvertDocuments method:
static void ConvertDocuments(IEnumerable<LEADDocument> documents, RasterImageFormat imageFormat)
{
using var converter = new DocumentConverter();
using var ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD);
ocrEngine.Startup(null, null, null, null);
converter.SetOcrEngineInstance(ocrEngine, false);
converter.SetDocumentWriterInstance(new DocumentWriter());
foreach (var document in documents)
{
var name = string.IsNullOrEmpty(document.Name) ? "Attachment" : document.Name;
string outputFile = Path.Combine(OutputDir, $"{name}.{RasterCodecs.GetExtension(imageFormat)}");
int count = 1;
while (File.Exists(outputFile))
outputFile = Path.Combine(OutputDir, $"{name}({count++}).{RasterCodecs.GetExtension(imageFormat)}");
var jobData = new DocumentConverterJobData
{
Document = document,
Cache = cache,
DocumentFormat = DocumentFormat.User,
RasterImageFormat = imageFormat,
RasterImageBitsPerPixel = 0,
OutputDocumentFileName = outputFile,
};
var job = converter.Jobs.CreateJob(jobData);
converter.Jobs.RunJob(job);
}
}
Using .net core & c# here.
I have a UI from which user can upload the Excel or CSV files. Once they upload this goes to my web api which handles the reading of the data from these files and returns json.
My Api code as:
[HttpPost("upload")]
public async Task<IActionResult> FileUpload(IFormFile file)
{
JArray data = new JArray();
using (ExcelPackage package = new ExcelPackage(file.OpenReadStream()))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
//Process, read from excel here and populate jarray
}
return Ok(data );
}
In my above code I am using EPPlus for reading the excel file. For excel file it works all fine but it cannot read csv file which is the limitation of EPPlus.
I searched and found another library CSVHelper: https://joshclose.github.io/CsvHelper/ The issue with this is it does vice versa and can read from CSV but not from Excel.
Is there any library available which supports reading from both.
Or would it be possible use EPPlus only but convert uploaded CSV to excel on the fly and then read. (please note I am not storing the excel file anywhere so cant use save as to save it as excel)
Any inputs please?
--Updated - Added code for reading data from excel---
int rowCount = worksheet.Dimension.End.Row;
int colCount = worksheet.Dimension.End.Column;
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
{
var rowValue = worksheet.Cells[row, col].Value;
}
}
//With the code suggested in the answer rowcount is always 1
You can use EPPLus and a MemoryStream for opening csv files into an ExcelPackage without writing to a file. Below is an example. You may have to change some of the the parameters based on your CSV file specs.
[HttpPost("upload")]
public async Task<IActionResult> FileUpload(IFormFile file)
{
var result = string.Empty;
string worksheetsName = "data";
bool firstRowIsHeader = false;
var format = new ExcelTextFormat();
format.Delimiter = ',';
format.TextQualifier = '"';
using (var reader = new System.IO.StreamReader(file.OpenReadStream()))
using (ExcelPackage package = new ExcelPackage())
{
result = reader.ReadToEnd();
ExcelWorksheet worksheet =
package.Workbook.Worksheets.Add(worksheetsName);
worksheet.Cells["A1"].LoadFromText(result, format, OfficeOpenXml.Table.TableStyles.Medium27, firstRowIsHeader);
}
}
Here's using Aspose, which is unfortunately not free, but wow it works great. My API is using the streaming capability with Content-Type: multipart/form-data rather than the IFormFile implementation:
[HttpPut]
[DisableFormValueModelBinding]
public async Task<IActionResult> UploadSpreadsheet()
{
if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
{
return BadRequest($"Expected a multipart request, but got {Request.ContentType}");
}
var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
var reader = new MultipartReader(boundary, HttpContext.Request.Body);
var section = (await reader.ReadNextSectionAsync()).AsFileSection();
//If you're doing CSV, you add this line:
LoadOptions loadOptions = new LoadOptions(LoadFormat.CSV);
var workbook = new Workbook(section.FileStream, loadOptions);
Cells cells = workbook.Worksheets[0].Cells;
var rows = cells.Rows.Cast<Row>().Where(x => !x.IsBlank);
//Do whatever else you want here
Please try with below code
private string uploadCSV(FileUpload fl)
{
string fileName = "";
serverLocation = Request.PhysicalApplicationPath + "ExcelFiles\\";
fileName = fl.PostedFile.FileName;
int FileSize = fl.PostedFile.ContentLength;
string contentType = fl.PostedFile.ContentType;
fl.PostedFile.SaveAs(serverLocation + fileName);
string rpath = string.Empty, dir = string.Empty;
HttpContext context = HttpContext.Current;
string baseUrl = context.Request.Url.Scheme + "://" + context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/') + '/';
try
{
rpath = serverLocation + fileName;//Server.MapPath(dir + fileName);
using (Stream InputStream = fl.PostedFile.InputStream)
{
Object o = new object();
lock (o)
{
byte[] buffer = new byte[InputStream.Length];
InputStream.Read(buffer, 0, (int)InputStream.Length);
lock (o)
{
File.WriteAllBytes(rpath, buffer);
buffer = null;
}
InputStream.Close();
}
}
}
catch (Exception ex)
{
lblSOTargetVal.Text = ex.Message.ToString();
}
return rpath;
}
Use the Open XML SDK package and add insert working solution for it.
Powerpoint shows "Unable to read an object" after I embed the excel into powerpoint file via openxml.
Am using a simple excel with a chart and a pptx created already.
This fails in both .NetCore and .NetFramework
Here is my code.
string PPTFileName = #"c:\tmp\Example04.pptx";
string spreadsheetFileName = #"c:\tmp\demoOut5.xlsx";
using (PresentationDocument myPresDoc = PresentationDocument.Open(PPTFileName, true))
{
SlidePart slidePartBookMark = null;
string chartPartIdBookMark = "";
foreach (var slidePart in myPresDoc.PresentationPart.SlideParts)
{
if (slidePart.ChartParts.Any())
{
slidePartBookMark = slidePart;
var chartPart = slidePart.ChartParts.First();
chartPartIdBookMark = slidePart.GetIdOfPart(chartPart);
slidePart.DeletePart(chartPart);
slidePart.Slide.Save();
break;
}
}
var newChartPart = slidePartBookMark.AddNewPart<ChartPart>(chartPartIdBookMark);
EmbeddedPackagePart embPackage = newChartPart
.AddNewPart<EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "rId1");
embPackage.FeedData(new FileStream(#"c:\tmp\demoOut4.xlsx", FileMode.Open, FileAccess.Read));
DocumentFormat.OpenXml.Drawing.Charts.ExternalData ed = new DocumentFormat.OpenXml.Drawing.Charts.ExternalData();
ed.Id = "rId1";
slidePartBookMark.Slide.Save();
myPresDoc.Close();
Console.WriteLine("Done");
Console.ReadKey();
}
Any help or direction would be appreciated. Thanks.
Ok so here is my problem. I am trying to fetch data from a database and output all the data to an excel spread sheet or even a text document.
Whichever is easier.
Eventually i want it to be in excel though.
I am pretty new to this and have been looking for multiple answers for going on three weeks.
Any help is appreciated.
//Export to excel
[HttpPost]
public ActionResult Download()
{
List<string> persons = new List<string> { };
using (SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=WebApplication1;Integrated Security=SSPI"))
using (SqlCommand cmd = new SqlCommand("SELECT RMAFormModels AS cusName FROM RMAFormModels ", connection))
{
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Check is the reader has any rows at all before starting to read.
if (reader.HasRows)
{
// Read advances to the next row.
while (reader.Read())
{
RMAFormModels p = new RMAFormModels();
// To avoid unexpected bugs access columns by name.
p.cusName = reader.GetString(reader.GetOrdinal("cusName"));
//p.FirstName = reader.GetString(reader.GetOrdinal("FirstName"));
// int middleNameIndex = reader.GetOrdinal("MiddleName");
// If a column is nullable always check for DBNull...
//if (!reader.IsDBNull(middleNameIndex))
// {
// p.MiddleName = reader.GetString(middleNameIndex);
// }
// p.LastName = reader.GetString(reader.GetOrdinal("LastName"));
// persons.Add(p);
}
}
}
}
// Use persons here...
// var name = collection.cusName;
//var date = collection.DatePurchased;
//var dateIssued = collection.DateIssued;
/* List<Lookup> collection = new List<Lookup>();
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = collection;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=ExcelTest.xlsx");
Response.ContentType = "application/vnd.ms-excel";
//Response.ContentType = "application / vnd.openxmlformats - officedocument.spreadsheetml.sheet";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
*/
//customer = new cusName();
// cusName = "Tod";
var string_with_your_data = persons ;
//List<>.ToCharArray(string_with_your_data);
var byteArray = Encoding.ASCII.GetBytes(string_with_your_data);
var stream = new MemoryStream(byteArray);
return File(stream, "text/plain", "your_file_name.txt"); // this goes to a file.txt
}
}`
It looks like you want this to be a web page that exports to excel. I recommend using an ApiController method that outputs an HttpResultMessage. Make the content be a CSV text representation of the table. Make the Content-Type be text/csv and add a file name to the http header section. In Windows anyone who has CSV files associated with Excel will have the option to open the downloaded file and it will automatically open into excel.
I have done this with ClosedXML nuget Package. I hope that it will be useful to you too.
add ClosedXML nuget Package to your project.
You will need to importClosedXML.Excel namespace
3.Export action
[HttpPost]
public FileResult Export()
{
DataTable dt = new DataTable("Grid");
dt.Columns.AddRange(new DataColumn[4] { new DataColumn("CustomerId"),
new DataColumn("ContactName"),
new DataColumn("City"),
new DataColumn("Country") });
var customers = GetCustomers(); //get customer from database;
foreach (var customer in customers)
{
dt.Rows.Add(customer.CustomerID, customer.ContactName, customer.City, customer.Country);
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx");
}
}
}
4.on the View
#using (Html.BeginForm("Export", "Home", FormMethod.Post))
{
<input type="submit" value="Export"/>
}