C # Summary of 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 will 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 /// /// Read data from Excel ////// /// /// Public static dataset getdatafromexcel (string excelpath, string sheetname) {dataset DS = new dataset (); string strconn = "provider = Microsoft. 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 ;}/// /// Replace word text ////// Document/// Content to be replacedPublic void replaceword (document DOC, Dictionary ARGs) {try {object first = 0; Object last = Doc. characters. count; 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, ref missingvalue, ref missingvalue) ;}} catch {return ;}}/// /// Word Document Resource release ////// Document for resource releasePublic 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 ;}}/// /// Create a Word file from the template ////// Template location and name/// 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 unkn Ow, 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 Export 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 a field of the ID card or other type is encountered, it is likely to be "truncated" after the Excel file is exported due to scientific notation. Therefore, it is necessary to process this long integer field. /// /// Filter low-level non-printable characters ////// /// 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. /// /// Generate an Excel file from dataset ////// Dataset/// File NamePublic 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, n Ull, null); excel. quit (); Excel = NULL; GC. collect ();} 3. search PDF File Creation guide in PDF to find the ready-made materials. The code and documents are relatively complete and clear, here is a simple demo -- generate a PDF document with a chapter with the content of the image. Implementation steps: 1) create a project in vs environment and reference icsharpcode. sharpziplib. DLL, itextsharp. DLL files 2) enter the following code in the button event: // set the layout to A4 size 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 = 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

C # Summary of operations on files in Word, Excel, PDF, and other formats.

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.