zoukankan      html  css  js  c++  java
  • Excel简单读写操作

    Excel的程序集来自与Excel,所以如果在C#中遇到自己不懂的东西,不妨打开Excel的VBA工具,录制宏然后查看其中的操作代码。虽然好多的功能都通过import特征引入到C#中,但是深层的属性和方法都没有实现(已动态对象存在)。

    这里我是从 .Sql中读取sql执行,并按照一定的格式写入Excel的。

    这里主要用到的Excel相关方法与类有:

    Microsoft.Office.Interop.Excel.Application//获取
    Microsoft.Office.Interop.Excel.Workbook//相当于一个Excel文件
    Microsoft.Office.Interop.Excel.Worksheet//相当于一个sheet

    Application.WorkBooks//所有打开的workbook

    WorkBooks.WorkSheets//工作表的所有sheet

    WorkBooks.Add()//添加一个(在内存中)workbook

    WorkSheets.Add()//在workbook中添加一个sheet

    WorkSheets.get_Range("a1:b5")//获取一个区域,区域可以是一个Cell也可以是Cell的集合。

    Range.Rows.Count//range的行数

    ws.Cells[1,2]="Cell值"//设置Cell的值

    WorkBook.SaveTo("path");//保存到指定文件

    WorkBook.Close()//关闭workbook

    Appliction.Quit()//关闭Excel进程

    Process.GetProcesses()//获取当前进程列表

    System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")//获取正在运行的对象的实例。

      1 public void FillExcel(string connStr,string sql,System.Data.SqlClient.SqlParameter[] parame,string formatfile,string saveTo,string fileName,bool allowRep) {
      2     string querystring;
      3     object Nothing = System.Reflection.Missing.Value;
      4     Microsoft.Office.Interop.Excel.Application app = null;
      5     Microsoft.Office.Interop.Excel.Workbook wb = null;
      6     Microsoft.Office.Interop.Excel.Worksheet ws = null;
      7     app = getAppliction();
      8     if (sql.Contains(@"") && System.IO.File.Exists(sql))
      9     {
     10         querystring = System.IO.File.ReadAllText(sql, Encoding.GetEncoding(936));//*.sql文件默认为gb2312编码
     11     }
     12     else {
     13         querystring = sql;
     14     }
     15     Dictionary<int, FileRule> formatrule = getFormatRule(formatfile);
     16     if (!System.IO.File.Exists(saveTo + @"" + fileName))
     17     {
     18                 
     19         wb = app.Workbooks.Add(Nothing);
     20         if (wb.Worksheets.Count == 0)
     21         {
     22             ws = wb.Worksheets.Add();
     23             ws.Name = "插入";
     24         }
     25         else {
     26             ws = wb.ActiveSheet;
     27         }
     28     }
     29     else {
     30         Console.WriteLine("此文件已经存在!" + saveTo + @"" + fileName);
     31     reinput:
     32         Console.WriteLine("是否覆盖?(Y:覆盖|N:打开并写入|L:另存在)");
     33         ConsoleKeyInfo ck = Console.ReadKey(true);
     34 
     35         if (ck.Key == ConsoleKey.Y)
     36         {
     37             System.IO.File.Delete(saveTo + @"" + fileName);
     38             wb = app.Workbooks.Add(Nothing);
     39             if (wb.Worksheets.Count == 0)
     40             {
     41                 ws = wb.Worksheets.Add();
     42             }
     43             else {
     44                 ws = wb.ActiveSheet;
     45             }
     46         }
     47         else if (ck.Key == ConsoleKey.N)
     48         {
     49             wb = app.Workbooks.Open(saveTo + @"" + fileName);
     50             ws = wb.Worksheets.Add();
     51         }
     52         else if (ck.Key == ConsoleKey.L)
     53         {
     54             string message = "请输入新的文件名:";
     55             bool isavalid=false;
     56             while (!isavalid) {
     57                 Console.WriteLine("请输入新的文件名:");
     58                 string fn= Console.ReadLine();
     59                 if (fn.TrimEnd().EndsWith(".xlsx") || fn.TrimEnd().EndsWith(".lsx"))
     60                 {
     61                     if (System.IO.File.Exists(fn))
     62                     {
     63                         isavalid = false;
     64                         message = "此文件在目录中已存在,请重新输入!";
     65                     }
     66                     else
     67                     {
     68                         app = new Microsoft.Office.Interop.Excel.Application();
     69                         wb = app.Workbooks.Add(Nothing);
     70                         if (wb.Worksheets.Count == 0)
     71                         {
     72                             ws = wb.Worksheets.Add();
     73                             ws.Name = "sheet1";
     74                         }
     75                         else
     76                         {
     77                             ws = wb.ActiveSheet;
     78                         }
     79                         fileName = fn;
     80                         isavalid = true;
     81                     }
     82                 }
     83                 else {
     84                     message = "文件后缀名错误!请从新输入。";
     85                 }
     86             }
     87         }
     88         else
     89         {
     90             goto reinput;
     91         }
     92     }
     93     System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
     94     conn.ConnectionString = connStr;
     95     int nowresultset=0;
     96     try {
     97         Console.WriteLine("正在尝试打开数据库连接.....");
     98         System.Data.SqlClient.SqlDataReader reader=null;
     99         conn.Open();
    100         try {
    101             if (parame == null)
    102                 reader = getReader(querystring, conn);
    103             else
    104                 reader = getReader(querystring, parame, conn);
    105             Console.WriteLine("数据库连接成功:" + conn.State.ToString() + "....");
    106             Console.WriteLine("数据读取成功,共获取到{0}列的数据",reader.FieldCount);
    107         }
    108         catch (System.Data.SqlClient.SqlException e) { 
    109             Console.WriteLine("语句执行出错!"+e.Message+"
    是否需要查看语句?(输入Y查看)");
    110             ConsoleKeyInfo ck= Console.ReadKey(true);
    111             if (ck.Key == ConsoleKey.Y)
    112             {
    113                 Console.WriteLine(querystring);
    114                 Console.Read();
    115             }
    116             throw e;
    117         }
    118         do
    119         {
    120             FileRule fe=null;
    121             if(!formatrule.TryGetValue(nowresultset, out fe))
    122             {
    123                 Console.WriteLine("nowResultset不存在:" + nowresultset.ToString() + "
    按任意键继续!");
    124                 Console.Read();
    125             }
    126             else {
    127                 Console.WriteLine("nowResultset为:" + fe.Range+"   "+fe.hasTitle.ToString() + "
    按任意键继续!");
    128             }
    129             if (fe != null)
    130             {
    131                 Microsoft.Office.Interop.Excel.Range rg;
    132                 if (fe.Range.Contains(":"))
    133                 {
    134                     rg = ws.get_Range(fe.Range.Split(':')[0], fe.Range.Split(':')[1]);//未初始化?
    135                 }
    136                 else
    137                 {
    138                     rg = ws.get_Range(fe.Range);
    139                 }
    140                 Console.WriteLine("将按要求写入{0}行{1}列数据。",rg.Row.ToString(),rg.Column.ToString());//
    141                 int colus = rg.Columns.Count,
    142                     startColu = rg.Column;
    143                 int rows = rg.Rows.Count,
    144                     startRow = rg.Row;
    145                 int sourceColus = reader.FieldCount;
    146                 int paddingRows = 0;
    147                 Console.WriteLine("开始遍历写入Excel!");
    148                 for (int r = 0; (rows==1&&colus==1)?(reader.Read()):((r < rows) && reader.Read()); r++)
    149                 {
    150                     for (int c = 0; (rows == 1 && colus == 1) ? c < sourceColus : (c < colus && c < sourceColus); c++)
    151                     {
    152                         if (fe.hasTitle == true && r == 0)
    153                         {
    154                             if (!fe.allowPivote)
    155                             {
    156                                 for (int nn = 0; (rows == 1 && colus == 1) ? nn< sourceColus : (nn < colus && c < sourceColus); nn++)
    157                                 {
    158                                     ws.Cells[startRow+r,startColu+nn]=reader.GetName(nn);
    159                                 }
    160                             }
    161                             else
    162                             {
    163                                 for (int nn = 0; nn < colus; nn++)
    164                                 {
    165                                     ws.Cells[startColu + nn, startRow + r] = reader.GetName(nn);
    166                                 }
    167                             }
    168                             paddingRows = 1;
    169                         }
    170                         if (fe.allowPivote)
    171                         {
    172                             if (!reader.IsDBNull(c) && reader[c].ToString() != "NULL" && reader[c].ToString() != "")
    173                             {
    174                                 ws.Cells[startColu + c + paddingRows, startRow + r] = reader[c].ToString();
    175                             }
    176                             else
    177                             {
    178                                 ws.Cells[startColu + c + paddingRows, startRow + r] = "";
    179                             }
    180                         }
    181                         if (!reader.IsDBNull(c) && reader[c].ToString() != "NULL" && reader[c].ToString() != "")//qlNullValueException
    182                         {
    183                             ws.Cells[startRow + r + paddingRows, startColu + c] = reader[c].ToString();
    184                         }
    185                         else
    186                         {
    187                             ws.Cells[startRow + r + paddingRows, startRow + c] = "";
    188                         }
    189                     }
    190                 }
    191             }
    192             else {
    193                 Console.WriteLine("这个文件并不需要写入!");
    194             }
    195             nowresultset++;
    196         }
    197         while (reader.NextResult());
    198         wb.SaveAs(saveTo + @"" + fileName);
    199         Console.WriteLine("文件创建为:{0}", wb.Path);
    200         Console.WriteLine("写入结束,任意键继续。");
    201         Console.ReadKey();
    202     }
    203     catch(System.Data.SqlClient.SqlException e){
    204         Console.WriteLine("数据库打开失败!
    是否查看异常信息?(Y继续)");
    205         ConsoleKeyInfo ki = Console.ReadKey(true);
    206         if (ki.Key == ConsoleKey.Y) {
    207             Console.WriteLine("异常信息为:
    "+e.Message);
    208             Console.Read();
    209         }
    210     }
    211     if (app != null) {
    212         Console.WriteLine("文件创建为:{0}", wb.Path);
    213         wb.Close();
    214         app.Quit();
    215     }
    216 }

    private Microsoft.Office.Interop.Excel.Application getAppliction() {
        Microsoft.Office.Interop.Excel.Application app;
        bool flag = false;
        foreach (var item in Process.GetProcesses())
        {
            if (item.ProcessName == "EXCEL")
            {
                flag = true;
                break;
            }
        }
        if (!flag)
        {
            app = new Microsoft.Office.Interop.Excel.Application();
        }
        else
        {
            try
            {
                object obj = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");//引用已在在跑的Excel
                app = obj as Microsoft.Office.Interop.Excel.Application;
            }
            catch (Exception e)
            {
                app = new Microsoft.Office.Interop.Excel.Application();
                Debug.WriteLine("发生异常,信息: {0}", "yuanakng", e.Message);
            }
        }
        return app;
    }
    }

    注:自己在里面加了些对自己有用的东西,format文件是自己写的规则,因为通用性不是太好所以不贴出。基础的文件读取写入也不足一提。非常简单的一个小例子。没有用ADO,可控制样式,很灵活。

  • 相关阅读:
    系统程序员成长计划内存管理(一)
    系统程序员成长计划工程管理(二)
    嵌入式GUI ftk0.3发布
    嵌入式GUI FTK设计与实现目录
    嵌入式GUI FTK设计与实现分层视图
    sql 临时表的问题
    解惑XP系统IIS无法添加映射之诡异现象
    C#高质量缩略图
    C#图片处理之另存为压缩质量可自己控制的JPEG
    SQL注入
  • 原文地址:https://www.cnblogs.com/Thancoo/p/5473579.html
Copyright © 2011-2022 走看看