Create new excel spreadsheet document using FileStream not MemoryStream in OpenXml - c#

I am writing code for creating excel spreadsheet using OpenXml. But wanted to use Filestream instead of MemoryStream in SpreadSheet.Create() method.
Note: With MemoryStream working correctly but for some reasons I need to get code working with Filestream.
Generating corrupted file when writing code like:
FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate);
using (SpreadsheetDocument document =
SpreadsheetDocument.Create(fs,SpreadsheetDocumentType.Workbook))
{
//worksheet code
}
If needed I can post worksheet code.

Try to use using to ensure that the file stream will be closed.
using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate))
{
using (SpreadsheetDocument document =
SpreadsheetDocument.Create(fs,SpreadsheetDocumentType.Workbook))
{
//worksheet code
}
}

Related

iText 7 and C# writing a PDF file from MemoryStream?

I have a PDF document (using iText 7/C# 4.01) that I am creating in a MemoryStream and at the end, I want to write it out to a file. Part of the reason I am creating it in a memory stream is that I want to stamp a header table and footers on it at the end and was hoping to avoid writing it to a file then reading the file back in, stamping, then writing out a new file (as the examples I keep finding on iText website seem to do). However, I seem to be having some sort of chicken/egg scenario in the below code. It seems that you have to Close() the document in order for iText to fully form it. However, if I Close() it, then I get an ObjectDisposedException when trying to write it (simplified example below). I have to be missing something simple here, right? Thanks
MemoryStream baos = new MemoryStream();
PdfWriter writer = new PdfWriter(baos);
PdfDocument pdfDocument = new PdfDocument(writer.SetSmartMode(true));
//writer.SetCloseStream(true);
//pdfDocument.SetCloseWriter(true);
//pdfDocument.SetCloseReader(true);
//pdfDocument.SetFlushUnusedObjects(true);
Document d = new Document(pdfDocument, iText.Kernel.Geom.PageSize.LETTER);
d.Add(new Paragraph("Hello world!"));
//d.Close();
FileStream file = new FileStream("C:\test.pdf",
FileMode.Create, FileAccess.Write);
baos. WriteTo(file);
file.Close();
//baos.Close();
//d.Close();
Try this
I dont have IDE for test, but i think this work
MemoryStream baos = new MemoryStream();
PdfWriter writer = new PdfWriter(baos);
PdfDocument pdfDocument = new PdfDocument(writer.SetSmartMode(true));
Document d = new Document(pdfDocument, iText.Kernel.Geom.PageSize.LETTER);
d.Add(new Paragraph("Hello world!"));
d.Close();
byte[] byte1 = baos.ToArray();
File(byte1, "application/pdf", "C:\\iTextTester\\test.pdf");

Generated file is still locked

I am using OpenXML SDK to generate and save a word document.
I am using a "Using" Block to create and dispose of the memory stream, and word document object when they are finished. However when trying to open to file i get the error that the file is still in use by another process.
Looking at Resource Monitor i have been able to find that it is my c# application still keeping it open.
When i close my application i can use the file
I have the following code.
private void button2_Click(object sender, EventArgs e)
{
// Create Stream
using (MemoryStream mem = new MemoryStream())
{
// Create Document
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body docBody = new Body();
mainPart.Document.Append(docBody);
wordDocument.SaveAs(#"E:\Report\word.docx");
// Add your docx content here
wordDocument.Close();
}
}
}
Am i correct in understanding that
using (MemoryStream mem = new MemoryStream())
should dispose of the MemoryStream when the block finishes, and therefore allow the file to be used by another process?
Thanks
SaveAs returns a new package object that represents the package stored in that file. You need to Close that package too.
wordDocument.SaveAs(#"E:\Report\word.docx").Close();

Filling out XFA PDF using iTextSharp, data not saving (C#)

I have an XFA PDF file (which I did not author). It's a third-party form which I'm trying to fill out. I filled out the form manually, then I used iTextSharp save the full XML DomDocument from it. Now I'm trying to apply that same XML file programmatically. However, the resulting PDF doesn't have any of the fields filled in. This is the code I'm using to apply the XML file:
PdfReader pdfReader = new PdfReader(inputPdf);
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(pdfReader, ms, '\0', true))
{
XfaForm xfaForm = new XfaForm(pdfReader);
XmlDocument doc = new XmlDocument();
doc.Load(inputXml);
xfaForm.DomDocument = doc;
xfaForm.Changed = true;
XfaForm.SetXfa(xfaForm, stamper.Reader, stamper.Writer);
}
var bytes = ms.ToArray();
System.IO.File.WriteAllBytes(outputPdf, bytes);
}
inputPdf is the path to the original empty PDF file.
inputXml is the path to the XML file extracted from the filled out PDF file. This is the entire XML file, and not just the datasets section.
What's interesting is that if I create the PdfStamper object like this instead:
new PdfStamper(pdfReader, ms);
then I see the data in the fields, but of course then I have the associated issues with not appending.
Any suggestions on what I might be doing wrong? I just can't seem to get any of the changes to the DomDocument to save.

How to Load Xml file whilelocking it using XDocument.Load() method?

I am using following two code to load an XML.Some other process is updating the same XML while i am trying to Load it.It's giving me below error in both case:-
The process cannot access the file
'D:\Projects\WriteOnXml\Xml\test.xml' because it is being used by
another process.
1)
using (FileStream xml = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
XDocument xdoc = XDocument.Load(xml);
}
2)
using (StreamReader sr = new StreamReader(dest))
{
xdoc = XDocument.Load(sr);
}
I want to load it while it is updating by some other process.
Any better approach.
have a look on that question:
c# xml.Load() locking file on disk causing errors
it seems that if you could use xml document it will work...

NPOI: Edit cell

I am using the following code to edit cells of an excel file but I dont see my changes in the escel file.
using (var fs = new FileStream(reconnFileName, FileMode.Open, FileAccess.ReadWrite))
{
HSSFWorkbook template = new HSSFWorkbook(fs, true);
ISheet sheet = template.GetSheetAt(0);
int rownumber=3;
foreach(StringBuilder cardHolderValue in cardHolderValues)
{
sheet.GetRow(rownumber).Cells[2].SetCellValue(cardHolderValue.ToString());
rownumber++;
}
}
And I can't find any Save() function in it to do so. Please let me know how can I save my edits.
Look at: http://dotnetslackers.com/articles/aspnet/Create-Excel-Spreadsheets-Using-NPOI.aspx#s7-conclusion. There is a Write method to save your excel file.
template.Write(new FileStream("c:/path", FileMode.Create, FileAccess.ReadWrite));

Categories