Home » x Other Posts » Creating PDF, Word, Excel, Outlook and Text files using C#

Creating PDF, Word, Excel, Outlook and Text files using C#

When you develop an application that needs exporting capability for several type of files, you should use some internal or external programming libraries. I will mention a few useful and free libraries for our exporting purposes.

Data Export

I don’t want to give much explanation about these libraries because you can find out easily If you want. My purpose is giving the summary (library name and basic code) about that.

Creating PDF File

Library: iTextSharp

Document <strong>document</strong> = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream
("C:\\test.pdf", System.IO.FileMode.Create));
document.Open();
document.Add(Paragraph p1 = new Paragraph("Hello World"););
document.Close();

Creating Word File

Library: Microsoft Word 14.0 Object Library (Internal)

Application app1 = new Application();
app1.Visible = true;
_Document doc1 = app1.Documents.Add();
doc1.Words.First.InsertBefore("Hello World");
doc1.SaveAs2("C:\\test.docx");

Creating Excel File

Library: Microsoft Excel 14.0 Object Library (Internal)

_Application app = new Application();
_Workbook workbook = app.Workbooks.Add(Type.Missing);
_Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Cells[1, 1] = "Hello World";
worksheet.Columns.AutoFit();
worksheet.Cells.HorizontalAlignment = Element.ALIGN_RIGHT;
workbook.SaveAs("C:\\test.xls", Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing,
Type.Missing, Type.Missing, Type.Missing);

Creating Outlook Files (New Mail Window)

Library: Microsoft Outlook 14.0 Object Library (Internal)

Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)<strong>oApp</strong>.CreateItem
(Outlook.OlItemType.olMailItem);
oMsg.HTMLBody = "Hello World";
oMsg.Display();

Creating Text Files

Library: System.IO (Internal)

System.IO.File.WriteAllText("C:\test.txt", "Hello World");

Notes

To open a file, use this code:

System.Diagnostics.Process.Start("test.pdf");

Before using any library (dll), do not forget to add it as a reference (Visual Studio > Solution Explorer > Right Click on References > Add Reference):

Add Reference Windows in Visual Studio
Add Reference Window in Visual Studio

Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

2 thoughts on “Creating PDF, Word, Excel, Outlook and Text files using C#”

Leave a Comment