write to memoerystream using epplus - c#

I have this assembly that basically creates an empty excel file using EPPLUS library. The file is created directly to desk, but i want first to write it in a memoerystream and then save the memoerystream to desk. I have this so far.
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplicationXLSX
{
class Program
{
static void Main(string[] args)
{
Createxlsx("XLSX");
}
public static void Createxlsx(string filename)
{
FileInfo newFile = new FileInfo("C:\\ConsoleApplicationXLSX\\" + filename + ".xlsx");
MemoryStream ms = new MemoryStream();
//create a package
using (ExcelPackage package = new ExcelPackage(ms))
{
package.Workbook.Worksheets.Add("worksheet");
package.Save();
}
}
}
}

Try
package.SaveAs(ms)
That should fill your stream with the excelfile-content.

Related

Close Excel in C# after the saving the file

I am using C# to write some information to an Excel file:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
using System.Globalization;
public void OpenExcel(string folder, string filename)
{
this.folder = folder;
this.filename = filename;
path = folder + #"\" + filename;
if (File.Exists(path) != true) //if the output file does not exists, create it
{
var app = new Microsoft.Office.Interop.Excel.Application();
var temp = app.Workbooks.Add();
temp.SaveAs(path);
temp.Close();
}
wb = excel.Workbooks.Open(path);
}
After I am done and have saved the file, I want to close it:
public void Close()
{
wb.Close(false);
excel.Quit();
excel.Application.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
workSheet = null;
wb = null;
excel = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
Both of the voids above are part of a class object named ExcelFile. However, when I use the code above and exit the program I have made, Excel still is left as a background process like in this question: C# closing Excel after using
I have seen that there are a few threads on stackoverflow on this topic, but no solution seems to work for me. I want to avoid killing all Excel processes if possible since this is a program that will make calculations using thread pool that will take hours to make.

Issue when open/save excel files with C#

I am trying to access excel modules with C# and I am having trouble after saving the excel file.
There are duplicate Thisworkbook and Sheets appearing as the picture below.
This only happens when the excel file has Modules while everything will be fine if the excel has only sheets in the project.
Here is the code which is nothing but only opening and saving the same file.
I am using WIN10/ VS2013 /EXCEL 2010.
Does anyone know why will this happen?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Vbe.Interop;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string filepath = #"C:\test.xls";
Excel._Application app = new Excel.Application();
Excel._Workbook workbook = app.Workbooks.Open(filepath);
workbook.SaveAs(filepath);
workbook.Close(true);
app.Quit();
}
}
}

Custom log4net azure blob appender stops logging when a file reaches 5.4MB

I am using the appender below to pipe our log messages to Azure with Log4Net.
Everything works fine, until the blob file reaches the size of 5.4MB. From than, no logs are appended to the log file anymore.
What is causing this? And how can I solve this?
namespace Digicreate.Core.Infrastructure.Logging
{
using System;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
// ReSharper disable once UnusedMember.Global
// justification: used in log4net configuration file
public class AzureBlobTxtFileAppender : BufferingAppenderSkeleton
{
private CloudStorageAccount _account;
...removed unimportant code...
protected override void SendBuffer(LoggingEvent[] events)
{
var appendBlobReference = _cloudBlobContainer.GetAppendBlobReference(Filename(DirectoryName));
if (!appendBlobReference.Exists())
{
appendBlobReference.CreateOrReplace();
}
Parallel.ForEach(events, ProcessEvent);
}
private static string Filename(string directoryName)
{
return $"{directoryName}/{DateTime.Today.ToString("yyyy_MM_dd", DateTimeFormatInfo.InvariantInfo)}.log.txt";
}
private void ProcessEvent(LoggingEvent loggingEvent)
{
using (var memoryStream = new MemoryStream())
{
using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8, 1024, true))
{
Layout.Format(streamWriter, loggingEvent);
streamWriter.Flush();
}
memoryStream.Position = 0;
_cloudBlobContainer
.GetAppendBlobReference(Filename(DirectoryName))
.AppendBlock(memoryStream);
}
}
}
}
According to Append Block documentation you might be hittin 50,000 block limit for a blob. Make sure to check for number of committed blocks before committing to the Blob using:
var blockCount = _cloudBlobContainer.GetAppendBlobReference(Filename(DirectoryName))
.Properties
.AppendBlobCommittedBlockCount;
and make sure it is not more than 50000.

System.IO.File is a type not a namespace

Im tring to create a file using a System.Io.File namespace howeever im using it on MVC witch im new to and i get this error when i publish my proyect "A using namespace directive can only be applied to namespaces; 'System.IO.File' is a type not a namespace"
This is my using Statement:
using System;
using System.Reflection;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.IO.File;
using System.Text;
using (var reader = System.IO.File.CreateText(#"C:\inetpub\wwwroot\procedimiento.txt"))
{
// Starting outer json array
reader.WriteLine("[");
for (var rowIndex = 0; rowIndex < myTable.Rows.Count; rowIndex++)
{
var row = myTable.Rows[rowIndex];
var rowValues = new List<string>(); // can be reused if needed
foreach (DataColumn column in myTable.Columns)
rowValues.Add(row[column].ToString());
var jsonRow = JsonConvert.SerializeObject(rowValues);
// Write current row
reader.Write(jsonRow);
// Add separating comma
if (rowIndex != myTable.Rows.Count - 1)
reader.WriteLine(",");
}
// End outer json array
reader.WriteLine("]");
}
the using keyword have different semantics depending on where it is located.
When put directly in a file it's to tell which namespaces to import. In that context you can not have a using statement for a class directly. Well. You can, but the syntax is different. MSDN.
The other usage is to dispose an object when it goes out of scope. In this case you can enter the fully qualified class name (namespace + class name) or just the class name. MSDN
In your code you have mixed the two.
Alternative 1
Completely remove the using statement in the file and just specify the full class name in the statement.
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Text;
//in your method
using (var reader = System.IO.File.CreateText(#"C:\inetpub\wwwroot\procedimiento.txt"))
Alternative 2
Remove the namespace from the statement and the class name from the directive:
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Text;
//in your method
using (var reader = File.CreateText(#"C:\inetpub\wwwroot\procedimiento.txt"))
Alternative 3
Rename the class using a directive. You typically use this when the compiler can't distinguish between different identifiers (like having the same class name in different imported namespaces).
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.IO;
using IoFile = System.IO.File; //this
using System.Text;
//in your method
using (var reader = IoFile.CreateText(#"C:\inetpub\wwwroot\procedimiento.txt"))
Your code is missing class and method declarations. System.IO.File is in fact a type and you shouldn't be referencing it in your using statements. All you need to reference is System.IO and then you can call File.CreateText().
using System;
using System.IO;
public class MyClass
{
public void CreateFile()
{
string path = #"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
}
}
MSDN on File.CreateText()
Try this.
using (StreamWriter sw = File.CreateText(fileName))
{
sw.WriteLine("New file created: {0}", DateTime.Now.ToString());
}

c# extract data from pdf file

I was trying to extract the data from pdf file using iTextSharp, but i go two errors. Actually I want to extract the data from pdf file and store it into database.
Here is my code:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.util.collections;
using System.Linq;
public partial class frm_CreatePDF : System.Web.UI.Page
{
public string P_InputStream3 = "~/My Documents/List Of Holidays 2012";
protected void Page_Load(object sender, EventArgs e)
{
ExtractText();
}
private string ExtractText()
{
PdfReader reader = new PdfReader(Server.MapPath(P_InputStream3));
string txt = PdfTextExtractor.GetTextFromPage(reader, 2, new LocationTextExtractionStrategy());
return txt;
}
}
And the error is:
The name 'PdfTextExtractor' does not exist in the current context
The type or namespace name 'LocationTextExtractionStrategy
Make sure you have brought the namespace in which those two classes are defined into scope by adding the using directive:
using iTextSharp.text.pdf.parser;
I guess you need to use another namespace where LocationTextExtractionStrategy is defined
First of all you need to add a reference to the ItextSharp dll, after wich you can add a using statement to acces the namespace that contains that static class
http://msdn.microsoft.com/en-us/library/wkze6zky%28v=vs.100%29.aspx
This is a late answer, but I've found what your issue is:
You are missing the iTextSharp.text.pdf.parser using statement. Add this below your using iTextSharp.text.pdf; code:
using iTextSharp.text.pdf.parser;
That should be able to find your LocationTextExtractionStrategy pretty well.
You can also just add iTextSharp.text.pdf.parser directly behind your LocationTextExtractionStrategy if you want.
string txt = PdfTextExtractor.GetTextFromPage(reader, 2, new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy());
But I would recommend the former. It's cleaner and easier to read.

Categories

Resources