• 多文档读写


    51CTO下载-C#读取doc,pdf,ppt文件

    C#读取doc,pdf,ppt文件
     
    doc  pdf ppt与 txt之间的转换 :
    组件的作用一般是将文件读出成字符格式,并不是单纯的转换文件名后缀,所以需要将读出的东西写入txt文件 。
     
    添加office引用
    .net中对office中的word及ppt进行编程时,确保安装office时已经安装了word,ppt可编程组件(自定义安装时可查看)或者安装“Microsoft Office 2003 Primary Interop Assemblies”
    安装后,在编程页面添加引用:
    添加引用-com—microsoft powerpoint object 11.0 libaray/word 11.0 object library;
    还得添加office组件
    using Microsoft.Office.Interop.Word;
    using Microsoft.Office.Interop.PowerPoint;
     
    using org.pdfbox.pdmodel;
    using org.pdfbox.util;
     
    using Microsoft.Office.Interop.Word;
    using Microsoft.Office.Interop.PowerPoint;
    public void pdf2txt(FileInfo file,FileInfo txtfile)
        {
            PDDocument doc = PDDocument.load(file.FullName);
            PDFTextStripper pdfStripper = new PDFTextStripper();
            string text = pdfStripper.getText(doc);
                StreamWriter swPdfChange = new StreamWriter(txtfile.FullName, false, Encoding.GetEncoding("gb2312"));
            swPdfChange.Write(text);
            swPdfChange.Close();
        }
     
    对于doc文件中的表格,读出的结果是去除掉了网格线,内容按行读取。
        public void word2text(FileInfo file,FileInfo txtfile)
        {
     
            object readOnly = true;
            object missing = System.Reflection.Missing.Value;
            object fileName = file.FullName;
            Microsoft.Office.Interop.Word.ApplicationClass wordapp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Document doc = wordapp.Documents.Open(ref fileName,
        ref missing, ref readOnly, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing);
            string text = doc.Content.Text;
            doc.Close(ref missing, ref missing, ref missing);
            wordapp.Quit(ref missing, ref missing, ref missing);
            StreamWriter swWordChange = new StreamWriter(txtfile.FullName, false, Encoding.GetEncoding("gb2312"));
            swWordChange.Write(text);
            swWordChange.Close();
     
        }
     
        public void ppt2txt(FileInfo file, FileInfo txtfile)
        {
             Microsoft.Office.Interop.PowerPoint.Application pa = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
            Microsoft.Office.Interop.PowerPoint.Presentation pp = pa.Presentations.Open(file.FullName,
                            Microsoft.Office.Core.MsoTriState.msoTrue,
                            Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoFalse);
            string pps = "";
            StreamWriter swPPtChange = new StreamWriter(txtfile.FullName, false, Encoding.GetEncoding("gb2312"));
            
            foreach (Microsoft.Office.Interop.PowerPoint.Slide slide in pp.Slides)
            {
                foreach (Microsoft.Office.Interop.PowerPoint.Shape shape in slide.Shapes)
                
                    pps += shape.TextFrame.TextRange.Text.ToString();
        
            }
            swPPtChange.Write(pps);
            swPPtChange.Close();
     
        
        }
     
    读取不同类型的文件 
        public StreamReader text2reader(FileInfo file)
        {
            StreamReader st = null;
            switch (file.Extension.ToLower())
            {
                case ".txt":
                    st = new StreamReader(file.FullName, Encoding.GetEncoding("gb2312"));
                    break;
                case ".doc":
                    FileInfo wordfile = new FileInfo(@"E:my programs200807programFileSearchApp_Dataword2txt.txt");//不能使用相对路径,想办法改进
                    word2text(file, wordfile);
                    st = new StreamReader(wordfile.FullName, Encoding.GetEncoding("gb2312"));
                    break;
                case ".pdf":
                    FileInfo pdffile = new FileInfo(@"E:my programs200807programFileSearchApp_Datapdf2txt.txt");
                    pdf2txt(file, pdffile);
                    st = new StreamReader(pdffile.FullName, Encoding.GetEncoding("gb2312"));
                    break;
                case".ppt":
                    FileInfo pptfile = new FileInfo(@"E:my programs200807programFileSearchApp_Datappt2txt.txt");
                    ppt2txt(file,pptfile);
                    st = new StreamReader(pptfile.FullName,Encoding.GetEncoding("gb2312"));
                    break;
            }
            return st;
        }
     
    View Code

    C# 多文档界面 页面切换

    //主界面窗体类文件
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using MyProjectBLL;
    namespace MyProject
    {
        public partial class FormIndex : Form
        {
            static User user = null;
            public FormIndex()
            {
                InitializeComponent();
            }
            private void FormIndex_Load(object sender, EventArgs e)
            {
                if (user == null)
                {
                    user = new User();
                }
                FormLogin formLogin = new FormLogin(user);  //主界面加载前调出登录界面
                formLogin.ShowDialog();
                user = User.QueryByName(user.user_name);  //验证登录用户
                if(user!=null)
                    this.txtUsername.Text = user.user_name;
                this.Location = new Point(10, 10);
                this.ShowInTaskbar = true;      //程序是否在系统工具栏显示
                this.WindowState = FormWindowState.Normal;  
                this.IsMdiContainer = true;      //窗体是否是父窗体(窗体容器)
            }
            private void 添加用户ToolStripMenuItem_Click(object sender, EventArgs e)//窗体工具栏上的图标的点击响应方法
            {
                for (int i = 0; i < this.MdiChildren.Length; i++)
                {
                    this.MdiChildren[i].Close();    //关闭所有子窗体
                }
                this.tstFormIndex.Text = "用户管理--添加用户"; //修改父窗体状态栏
                FormAddUser formAddUser = new FormAddUser(user);//打开想要打开的窗体作为子窗体  
                formAddUser.MdiParent = this;
                formAddUser.Dock = DockStyle.Fill;
                formAddUser.MaximizeBox = true;
                formAddUser.Show();        //显示子窗体 
            }
      private void 查询用户ToolStripMenuItem_Click(object sender, EventArgs e)//窗体工具栏上的图标的点击响应方法
            {
                for (int i = 0; i < this.MdiChildren.Length; i++)
                {
                    this.MdiChildren[i].Close();    //关闭所有子窗体
                }
                this.tstFormIndex.Text = "用户管理--查询用户"; //修改父窗体状态栏
                FormQueryUser formQueryUser = new FormQueryUser(user);//打开想要打开的窗体作为子窗体  
                formQueryUser.MdiParent = this;
                formQueryUser.Dock = DockStyle.Fill;
                formQueryUser.MaximizeBox = true;
                formQueryUser.Show();       //显示子窗体 
            }
     }
    }
     
    View Code

    C#读取PDF ——PDFBox使用下载

    一、下载PDFBox
    
    访问网址http://sourceforge.net/projects/pdfbox/
    二、引用动态链接库
    
        解压缩下载的PDFBox,找到其中的Bin目录,需要在项目中添加引用的dll文件有:
    IKVM.GNU.Classpath.dll
        PDFBox-0.7.3.dll
        FontBox-0.1.0-dev.dll
        IKVM.Runtime.dll
    将以上4个文件引用到项目中,在文件中需要引入以下2个命名空间:
    using org.pdfbox.pdmodel;
        using org.pdfbox.util;
    
    三、API的使用方法
    
    请见以下示例:
    
    using org.pdfbox.pdmodel;
    using org.pdfbox.util;
    
    public void pdf2txt(FileInfo file,FileInfo txtfile)
    
        {
    
            PDDocument doc = PDDocument.load(file.FullName);
    
            PDFTextStripper pdfStripper = new PDFTextStripper();
    
            string text = pdfStripper.getText(doc);
    
                StreamWriter swPdfChange = new StreamWriter(txtfile.FullName, false, Encoding.GetEncoding(“gb2312″));
    
            swPdfChange.Write(text);
    
            swPdfChange.Close();
    
        }
    ———————–关于最新版本另一种说法
    需要复制并加载如下5个DLL文件到bin目录下面
    # IKVM.GNU.Classpath.dll
    # PDFBox-0.7.3.dll
    # FontBox-0.1.0-dev.dll
    # IKVM.Runtime.dll
    # bcprov-jdk14-132.dll
    
    实例代码:
    using System;
    
    using org.pdfbox.pdmodel;
    
    using org.pdfbox.util;
    
    namespace PDFReader
    
    {
    
        class Program
    
        {
    
            static void Main(string[] args)
    
            {
    
                PDDocument doc = PDDocument.load(“lopreacamasa.pdf”);
    
                PDFTextStripper pdfStripper = new PDFTextStripper();
    
                Console.Write(pdfStripper.getText(doc));
    
            }
    
        }
    
    }
    ====================
    using org.pdfbox.pdmodel;
    using org.pdfbox.util;
    using org.pdfbox;
    
        public string PdfReader(string filename)
        {
            string fullname = DocPath + filename;
            PDDocument doc = PDDocument.load(fullname);
            PDFTextStripper stripper = new PDFTextStripper();
            string pdoc = stripper.getText(doc);
            return pdoc;
        }
    View Code

    C#读取doc,pdf,ppt文件

    doc  pdf ppt与 txt之间的转换 :
    组件的作用一般是将文件读出成字符格式,并不是单纯的转换文件名后缀,所以需要将读出的东西写入txt文件 。
    添加office引用
    .net中对office中的word及ppt进行编程时,确保安装office时已经安装了word,ppt可编程组件(自定义安装时可查看)或者安装“Microsoft Office 2003 Primary Interop Assemblies”
    安装后,在编程页面添加引用:
    添加引用-com—microsoft powerpoint object 11.0 libaray/word 11.0 object library;
    还得添加office组件
    using Microsoft.Office.Interop.Word;
    using Microsoft.Office.Interop.PowerPoint;
    using org.pdfbox.pdmodel;                     
    using org.pdfbox.util;
    using Microsoft.Office.Interop.Word;
    using Microsoft.Office.Interop.PowerPoint;
    public void pdf2txt(FileInfo file,FileInfo txtfile)
        {
            PDDocument doc = PDDocument.load(file.FullName);
            PDFTextStripper pdfStripper = new PDFTextStripper();
            string text = pdfStripper.getText(doc);
                StreamWriter swPdfChange = new StreamWriter(txtfile.FullName, false, Encoding.GetEncoding("gb2312"));
            swPdfChange.Write(text);
            swPdfChange.Close();
        }
    对于doc文件中的表格,读出的结果是去除掉了网格线,内容按行读取。
        public void word2text(FileInfo file,FileInfo txtfile)
        {
            object readOnly = true;
            object missing = System.Reflection.Missing.Value;
            object fileName = file.FullName;
            Microsoft.Office.Interop.Word.ApplicationClass wordapp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Document doc = wordapp.Documents.Open(ref fileName,
        ref missing, ref readOnly, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing);
            string text = doc.Content.Text;
            doc.Close(ref missing, ref missing, ref missing);
            wordapp.Quit(ref missing, ref missing, ref missing);
            StreamWriter swWordChange = new StreamWriter(txtfile.FullName, false, Encoding.GetEncoding("gb2312"));
            swWordChange.Write(text);
            swWordChange.Close();
        }
        public void ppt2txt(FileInfo file, FileInfo txtfile)
        {
             Microsoft.Office.Interop.PowerPoint.Application pa = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
            Microsoft.Office.Interop.PowerPoint.Presentation pp = pa.Presentations.Open(file.FullName,
                            Microsoft.Office.Core.MsoTriState.msoTrue,
                            Microsoft.Office.Core.MsoTriState.msoFalse,
                            Microsoft.Office.Core.MsoTriState.msoFalse);
            string pps = "";
            StreamWriter swPPtChange = new StreamWriter(txtfile.FullName, false, Encoding.GetEncoding("gb2312"));
           
            foreach (Microsoft.Office.Interop.PowerPoint.Slide slide in pp.Slides)
            {
                foreach (Microsoft.Office.Interop.PowerPoint.Shape shape in slide.Shapes)
               
                    pps += shape.TextFrame.TextRange.Text.ToString();
       
            }
            swPPtChange.Write(pps);
            swPPtChange.Close();
       
        }
    读取不同类型的文件
        public StreamReader text2reader(FileInfo file)
        {
            StreamReader st = null;
            switch (file.Extension.ToLower())
            {
                case ".txt":
                    st = new StreamReader(file.FullName, Encoding.GetEncoding("gb2312"));
                    break;
                case ".doc":
                    FileInfo wordfile = new FileInfo(@"E:my programs200807programFileSearchApp_Dataword2txt.txt");//不能使用相对路径,想办法改进
                    word2text(file, wordfile);
                    st = new StreamReader(wordfile.FullName, Encoding.GetEncoding("gb2312"));
                    break;
                case ".pdf":
                    FileInfo pdffile = new FileInfo(@"E:my programs200807programFileSearchApp_Datapdf2txt.txt");
                    pdf2txt(file, pdffile);
                    st = new StreamReader(pdffile.FullName, Encoding.GetEncoding("gb2312"));
                    break;
                case".ppt":
                    FileInfo pptfile = new FileInfo(@"E:my programs200807programFileSearchApp_Datappt2txt.txt");
                    ppt2txt(file,pptfile);
                    st = new StreamReader(pptfile.FullName,Encoding.GetEncoding("gb2312"));
                    break;
            }
            return st;
        }
     
    View Code

    C#读取word.doc,docx

    C#读取word.doc,docx
    引用com里的Microsoft.Office.Interop.Word;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.Office.Interop.Word;
     
    namespace WordDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                object oMissing = System.Reflection.Missing.Value;
                Application app = new Application();
                app.Visible = false;
                object fileName = @"C:UsersdujianyuDesktop2011111811125930.doc";
                Document doc = new Document();
                object format = WdOpenFormat.wdOpenFormatDocument;
                doc = app.Documents.Open(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                string content = doc.Content.Text.ToString();
                doc.Close(ref oMissing, ref oMissing, ref oMissing);
                app.Quit(ref oMissing, ref oMissing, ref oMissing);
     
                int i = 0;
            }
        }
    }
    View Code

    C#怎样读取doc文档

    需要先添加对Microsoft.Office.Interop.word的引用
    class ReadDoc
        {
            public void Read()
            {
                object readOnly = true;
                object missing = System.Reflection.Missing.Value;
                object fileName = "E:\1.docx";
                //初始化word程序
                ApplicationClass wordapp = new ApplicationClass();
                //打开指定的doc文件
                Document doc = wordapp.Documents.Open(ref fileName,
            ref missing, ref readOnly, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing);
                //读取指定的doc文件文本
                string text = doc.Content.Text;
                //读取指定的doc文件图片
                InlineShapes ils = doc.InlineShapes;
                foreach (InlineShape temp in ils)
                {
                    //选择图片
                    temp.Select();
                    //将图片放入剪贴板
                    wordapp.Selection.Copy();
                    //这里可写对图片的处理
                    System.Drawing.Image img = System.Windows.Forms.Clipboard.GetImage();
                    img.Save("E:\2.jpg");
                }
                //关闭打开的doc文档
                doc.Close(ref missing, ref missing, ref missing);
                //退出word程序
                wordapp.Quit(ref missing, ref missing, ref missing);
                //StreamWriter swWordChange = new StreamWriter(txtfile.FullName, false, Encoding.GetEncoding("gb2312"));
                //swWordChange.Write(text);
                //swWordChange.Close();
    
            }
        }
    View Code

    C#怎样读取doc文档的内容?

    办法1、转成html 读取文本文件,但某些word的内容会丢失,代码参见
    http://dotnet.aspx.cc/article/13c874e4-7fc7-4fd1-8cf6-de9ef4469a9c/read.aspx
     
    办法2,使用word提供的接口进行读取
     
     SDK文档在
    http://msdn.microsoft.com/en-us/library/bb726434(office.12).aspx
     try 
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader("C:TestFile.doc")) 
                {
                    String line;
                    // Read and display lines from the file until the end of 
                    // the file is reached.
                    while ((line = sr.ReadLine()) != null) 
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            catch (Exception e) 
            {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
     
     
     
     
    将Word文档转化为HTML格式的文档
    利用Word.Application提供的方法,可以很轻易地将Word文档转化为HTML等其它格式,下面就是实现的全部的代码。注意,必须先添加引用:
    
    说明:以上代码为Office2000环境下的代码,如果是Office XP或者Office 2003,您必须引用不同的Microsoft Word Object Library,同时,docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,null, doc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML});参数的多少也可能不同,具体要参照:
    http://msdn.microsoft.com/library/en-us/dnanchor/html/odc_ancoffice.asp
    Visual C#
    WordToHtml.aspx
     
    <%@ Page language="c#" Codebehind="WordToHtml.aspx.cs" AutoEventWireup="false"
     Inherits="aspxWebcs.WordToHtml" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
      <HEAD>
        <title>WordToHtml</title>
        <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        <meta name="CODE_LANGUAGE" Content="C#">
        <meta name="vs_defaultClientScript" content="JavaScript">
        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
        </form>
      </body>
    </HTML>
    WordToHtml.aspx.cs
     
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using Office;
     
    namespace aspxWebcs
    {
    /// <summary>
    /// WordToHtml 的摘要说明。
    /// 首先要添加引用:Microsoft Word 9.0 Object Library
    /// </summary>
    public class WordToHtml : System.Web.UI.Page
    {
      private void Page_Load(object sender, System.EventArgs e)
      {
        // 在此处放置用户代码以初始化页面
        Word.ApplicationClass word = new Word.ApplicationClass();
        Type wordType = word.GetType();
        Word.Documents docs = word.Documents;
     
        // 打开文件
        Type docsType = docs.GetType();
        object fileName = "d:\tmp\aaa.doc";
        Word.Document doc = (Word.Document)docsType.InvokeMember("Open",
        System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] {fileName, true, true});
              
        // 转换格式,另存为
        Type docType = doc.GetType();
        object saveFileName = "d:\tmp\aaa.html";
        //下面是Microsoft Word 9 Object Library的写法,如果是10,可能写成:
        /*
        docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
         null, doc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML});
        */
        ///其它格式:
        ///wdFormatHTML
        ///wdFormatDocument
        ///wdFormatDOSText
        ///wdFormatDOSTextLineBreaks
        ///wdFormatEncodedText
        ///wdFormatRTF
        ///wdFormatTemplate
        ///wdFormatText
        ///wdFormatTextLineBreaks
        ///wdFormatUnicodeText
        docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
         null, doc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML});
     
        // 退出 Word
        wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod,
         null, word, null);
    }
     
    #region Web 窗体设计器生成的代码
    override protected void OnInit(EventArgs e)
    {
    //
    // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
    //
    InitializeComponent();
    base.OnInit(e);
    }
     
    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {    
    this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
    }
    }
     
    View Code

    两招搞定C#读取Excel文件

    C#读取Excel文件方法一:直接读取(这种直接读取单元格的方法释放很重要)
    1. Excel.Applicationexcel=null;  
    2. Excel.Workbookswbs=null;  
    3. Excel.Workbookwb=null;  
    4. Excel.Worksheetws=null;  
    5. Excel.Rangerange1=null;  
    6. objectNothing=System.Reflection.Missing.Value;  
    7.  
    8. try  
    9. {  
    10. excel=newExcel.Application();  
    11. excel.UserControl=true;  
    12. excel.DisplayAlerts=false;  
    13.  
    14. excel.Application.Workbooks.Open(this.  
    15. FilePath,Nothing,Nothing,Nothing,Nothing,  
    16. Nothing,Nothing,Nothing,Nothing,Nothing,  
    17. Nothing,Nothing,Nothing);  
    18.  
    19. wbs=excel.Workbooks;  
    20. wb=wbs[1];  
    21. ws=(Excel.Worksheet)wb.Worksheets["Sheet2"];  
    22.  
    23.  
    24. introwCount=ws.UsedRange.Rows.Count;  
    25. intcolCount=ws.UsedRange.Columns.Count;  
    26. if(rowCount<=0)  
    27. thrownewInvalidFormatException  
    28. ("文件中没有数据记录");  
    29. if(colCount<4)  
    30. thrownewInvalidFormatException  
    31. ("字段个数不对");  
    32.  
    33. for(inti=0;i{  
    34. this.rowNo=i+1;  
    35. object[]row=newobject[4];  
    36. for(intj=0;j<4;j++)  
    37. {  
    38. range1=ws.get_Range(ws.Cells[i+2,j+1],  
    39. ws.Cells[i+2,j+1]);  
    40. row[j]=range1.Value;  
    41.  
    42. if(row[0]==null)  
    43. {  
    44. this.isNullRecord++;  
    45. break;  
    46. }  
    47. }  
    48.  
    49. if(this.isNullRecord>0)  
    50. continue;  
    51.  
    52. DataRowdataRow=this.readExcel(row);  
    53.  
    54. if(this.isNullRecord==1)  
    55. continue;  
    56.  
    57. if(this.verifyData(dataRow)==false)  
    58. errFlag++;  
    59.  
    60. this.updateTableCurr(dataRow);  
    61. }  
    62. }  
    63. finally  
    64. {  
    65. if(excel!=null)  
    66. {  
    67. if(wbs!=null)  
    68. {  
    69. if(wb!=null)  
    70. {  
    71. if(ws!=null)  
    72. {  
    73. if(range1!=null)  
    74. {  
    75. System.Runtime.InteropServices.Marshal.  
    76. ReleaseComObject(range1);  
    77. range1=null;  
    78. }  
    79. System.Runtime.InteropServices.Marshal.  
    80. ReleaseComObject(ws);  
    81. ws=null;  
    82. }  
    83. wb.Close(false,Nothing,Nothing);  
    84. System.Runtime.InteropServices.Marshal.  
    85. ReleaseComObject(wb);  
    86. wb=null;  
    87. }  
    88. wbs.Close();  
    89. System.Runtime.InteropServices.Marshal.  
    90. ReleaseComObject(wbs);  
    91. wbs=null;  
    92. }  
    93. excel.Application.Workbooks.Close();  
    94. excel.Quit();  
    95. System.Runtime.InteropServices.Marshal.  
    96. ReleaseComObject(excel);  
    97. excel=null;  
    98. GC.Collect();  
    99. }  
    100. }  
    C#读取Excel文件方法二:通过OleDb连接,把excel文件作为数据源来读取(这里是fill进dataset,也可以返回OleDbDataReader来逐行读,数据较快)
    注:这种方法容易把混合型的字段作为null值读取进来,解决办法是改造连接字符串
    1. strConn = "Provider=Microsoft.Jet.  
    2. OLEDB.4.0;Data Source=C:\Erp1912.xls;Extended   
    3. Properties='Excel8.0;HDR=Yes;IMEX=1'";  
    通过Imex=1来把混合型作为文本型读取,避免null值,来实现C#读取Excel文件
    1. privateDataSetimportExcelToDataSet  
    2. (stringFilePath)  
    3. {  
    4. stringstrConn;  
    5. strConn="Provider=Microsoft.Jet.  
    6. OLEDB.4.0;"+"DataSource="+FilePath+";  
    7. ExtendedProperties=Excel8.0;";  
    8. OleDbConnectionconn=newOleDbConnection  
    9. (strConn);  
    10. OleDbDataAdaptermyCommand=newOleDbDataAdapter  
    11. ("SELECT*FROM[Sheet1$]",strConn);  
    12. DataSetmyDataSet=newDataSet();  
    13. try  
    14. {  
    15. myCommand.Fill(myDataSet);  
    16. }  
    17. catch(Exceptionex)  
    18. {  
    19. thrownewInvalidFormatException  
    20. ("该Excel文件的工作表的名字不正确,"+ex.Message);  
    21. }  
    22. returnmyDataSet;  
    23. } 
     
    View Code

    实训一 概述

    实训一:C#概述
    一、 实训目的
    1、掌握VS.NET和MSDN安装,熟悉VS.NET集成开发环境及MSDN帮助文档的使用。
    2、了解.NET平台和.NET框架结构。
    3、掌握类库和命名空间的使用。
    4、掌握创建控制台应用程序。
    二、 实训内容
    1、画一个.NET框架结构图
    (1) 训练要点
    Ø 理解.NET框架的构成
    Ø 理解每个部分的功能
    (2) 需求说明
    Ø 用纸或计算机画出.NET框架结构图
    Ø 要求采用默写方式
    Ø 使用简单文字简单描述各部分的功能。
    (3) 实现思路及关键代码
    Ø 根据理论课知识整体理解框架的构成
    Ø 操作系统
    Ø CLR
    Ø 框架类库
    Ø 托管语言
    Ø CLR包含两大部分:CLS、CTS
    Ø 框架类库包含基本类库、用于描述数据的ADO.NET和XML、用于描述应用程序的ASP.NET、WebService、Winforms。
    参考解决方案如图1所示
    
     
    图1. .NET框架结构图
    2、做连线游戏,指出左侧命名空间的主要用途
    (1) 训练要点
    了解主要命名空间的功能
    (2) 需求说明
    在右侧找出左侧命名空间的主要功能,用直线连接。
    命名空间                       主要用途
    System.Data                    引入开发Windows应用程序类
    System.Windows.Forms           泛型
    System.Collections.Generic     用于访问ADO.NET
    System.Net                     提供系统的安全控制功能
    System.Security                可以对网络协议进行编程
    3、编写一个控制台程序Hello
    (1) 程序需求
    输出两行结果:Hello,My name is LiNing, This is my first csharp program;我的C#学习之旅开始了。
    (2) 参考代码
     如下所示:
    using System;
    using System.Collections.Generic;
    using System.Text;
    namespace Hello
    {
        class Hello
        {
            static void Main()
            {
                Console.WriteLine("Hello, My name is LiNing, This is my first csharp
    program");
                Console.WriteLine("我的c#学习之旅开始了");
                Console.ReadLine();
            }
        }
    }
    三、 作业
    1、搭建学习开发环境:VS2008+SQL Server2005开发版+Office2007+PDF阅读器.
    2、安装VS2008及熟悉VS2008开发环境:http://book.51cto.com/art/201008/215864.htm
    四、 课后问题
    1、类库与C/C++的库函数或者头文件有什么异同?
    2、查阅MSDN,查找Console类的常用方法及其用途?
     
    View Code
  • 相关阅读:
    Go module学习笔记
    java并发基础及原理
    java并发之内存模型
    https理论及实践
    Mysql查询结果导出Excel表
    mysql清空表数据并重置自增ID
    html a标签链接点击闪动问题解决
    rocketmq-console控制台管理界面配置
    nginx多层反代配置变量proxy_set_header
    nginx 实现浏览器文件下载服务
  • 原文地址:https://www.cnblogs.com/blogpro/p/11458274.html
Copyright © 2020-2023  润新知