C # operations on files in word, excel, pdf, and other formats

Source: Internet
Author: User
Tags printable characters

I. word

This is a business logic processing class I wrote before at work. There are many file operations in it. Here I mainly focus on C #'s operations on word. The methods can be used directly, mainly through the dot template of word to create word, replace word and other operations.

Namespace Excel2Word {public class BLL {private Microsoft. office. interop. word. application app = null; // global variable word application // <summary> /// read data from Excel /// </summary> /// <param name = "excelPath"> </param> /// <param name = "sheetName"> </param> /// <returns> </returns> public static DataSet GetDataFromExcel (string excelPath, string sheetName) {DataSet ds = new DataSet (); string strConn = "Provider = Microso Ft. jet. oleDb.4.0; Data Source = "+ excelPath. toString (). trim () + "; Extended Properties = Excel 8.0;"; try {using (OleDbConnection conn = new OleDbConnection (strConn) {conn. open (); OleDbDataAdapter oda = new OleDbDataAdapter ("select * from [" + sheetName + "]", conn); oda. fill (ds) ;}} catch {throw new Exception ("an Exception occurred when retrieving Excel Data... ");} return ds;} // <summary> // replace Word text /// </summary> // <p Aram name = "doc"> Document </param> // <param name = "args"> content to be replaced </param> public void ReplaceWord (Document doc, dictionary <string, string> args) {try {object first = 0; object last = doc. characters. count; Range range = doc. range (ref first, ref last); Microsoft. office. interop. word. find finder = range. find; finder. clearFormatting (); object missingValue = Type. missing; object replaceArea = Microsoft. office. Interop. word. wdReplace. wdReplaceAll; foreach (var item in args) {object findStr = "{" + item. key. trim () + "}"; object replaceStr = item. value. trim (); // Replace the content finder. execute (ref findStr, ref missingValue, ref replaceStr, ref replaceArea, ref missingValue, ref missingValue, r Ef missingValue, ref missingValue) ;}} catch {return ;}} /// <summary> // release a Word document resource /// </summary> /// <param name = "doc"> public void DisposeWord (Document doc) {try {object oMissing = System. reflection. missing. value; if (doc! = Null) {// close the Word and recycle the resource doc. close (ref oMissing, ref oMissing, ref oMissing); System. runtime. interopServices. marshal. releaseComObject (doc); doc = null;} if (app! = Null) {app. quit (ref oMissing, ref oMissing, ref oMissing); System. runtime. interopServices. marshal. releaseComObject (app); app = null; GC. collect () ;}} catch {return ;}} /// <summary> /// create a Word file from the template /// </summary> /// <param name = "fileName"> template location and name </param> /// <returns> </returns> public Document CreateWord (string fileName, string dsr) {try {app = new Microsoft. office. interop. word. application (); // open the word program Document doc = new Document (); // create the word object unknow = Type. missing; string date = DateTime. now. tow.datestring (); object savefilename = @ "D: \" + dsr + ". doc "; // save path object File = fileName; app. visible = false; // set the word program to invisible doc = app. documents. open (ref File, ref unknow, ref unknow, ref unknow, ref unknow); // open the Word document doc. saveAs (ref savefilename, ref unknow, ref unknow, ref unknow, ref unknow); // Save the Word document return doc;} catch {return null ;}}}}

Ii. excel

In webform, export the excel Code:

public void ExportResult(DataTable dt, string excelName) {     Response.Clear();     Response.Charset = "";     Response.ContentType = "applicationnd.ms-xls";     StringWriter sw = new StringWriter();     HtmlTextWriter htmlWrite = new HtmlTextWriter(sw);                        DataGrid dg = new DataGrid();     dg.DataSource = dt;     dg.DataBind();     dg.RenderControl(htmlWrite);     Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(excelName));     Response.Write(sw.ToString());     Response.End(); }

If you encounter fields of different types such as ID card, it is very likely to be "truncated" after exporting excel due to scientific notation, so it is necessary to process such long integer fields.

/// <Summary> /// filter low-level non-printable characters /// </summary> /// <param name = "tmp"> </param> // <returns> </returns> private string ReplaceLowOrderASCIICharacters (string tmp) {StringBuilder info = new StringBuilder (); foreach (char cc in tmp) {int ss = (int) cc; if (ss> = 0) & (ss <= 8) | (ss> = 11) & (ss <= 12) | (ss> = 14) & (ss <= 32) info. appendFormat ("", ss); else info. append (cc);} return info. toString ();}

In winform, the client generates the excel Code:

The premise is to install the office. The principle is to generate an excel file through the office process.

/// <Summary> /// generate an Excel file from DataSet /// </summary> /// <param name = "ds"> DataSet </param> // <param name = "strExcelFileName"> file name </param> public void ExportExcelByDataSet (DataSet ds, string strExcelFileName) {Microsoft. office. interop. excel. application excel = new Microsoft. office. interop. excel. application (); int rowIndex = 1; int colIndex = 0; excel. application. workbooks. add (true); DataTable dt = ds. tables [0]; foreach (DataColumn col in dt. columns) {colIndex ++; excel. cells [1, colIndex] = col. columnName;} foreach (DataRow row in dt. rows) {rowIndex ++; colIndex = 0; foreach (DataColumn col in dt. columns) {colIndex ++; excel. cells [rowIndex, colIndex] = row [col. columnName]. toString () ;}} excel. visible = false; excel. activeWorkbook. saveAs (strExcelFileName + ". XLS ", Microsoft. office. interop. excel. xlFileFormat. xlExcel9795, null, null, false, false, Microsoft. office. interop. excel. xlSaveAsAccessMode. xlNoChange, null, null); excel. quit (); excel = null; GC. collect ();}

3. pdf

Search "pdf file creation Guide" to find the ready-made materials. The code and documentation are relatively complete and clear. Here, we will make a simple demo to generate a section with the chapter, the content is a pdf document of the image.

Steps:

1) create a project in the vs environment and reference the two dll files ICSharpCode. SharpZipLib. dll and itextsharp. dll.

2) enter the following code in the button event:

// Set the layout to A4 size Document document = new Document (PageSize. a4); // create a testbench file named internal writer. getInstance (document, new FileStream ("testrunner", FileMode. create); document. open (); // Open the pdf document try {string [] images = Directory. getFiles ("test/"); for (int I = 0; I <images. length; I ++) {// define Chapter chapter Chapter = new Chapter (new Paragraph (images [I]), I + 1); // Add chapter document. add (chapter); // obtain the image iTextSharp. text. image tempImage = iTextSharp. text. image. getInstance (images [I]); // set the image size to 70% tempImage of the source image. scalePercent (70); // Add the image document to the document. add (tempImage); // create a document. newPage () ;}} catch (Exception ex) {throw ex;} document. close (); // Close the pdf document

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.