zoukankan      html  css  js  c++  java
  • 读取Excel文件中的单元格的内容和颜色

    怎样读取Excel文件中的单元格的内容和颜色


    先创建一个Excel文件,在A1和A2中随意输入内容,设置A1的字体颜色为红色,A2的背景为黄色。
    需要 using Excel = Microsoft.Office.Interop.Excel;
    或者using Microsoft.Excel;

                string file = @"E:	est.xls";            //测试文件
                Excel.Application excel = null;
                Excel.Workbook wkb = null;
                try
                {
                    excel = new Excel.Application();
                    wkb = excel.Workbooks.Open(file);
                    Excel.Sheets sheets = wkb.Worksheets;
                    Excel.Worksheet sheet = null;
                    if (sheets.Count > 0)
                        sheet = sheets[1] as Excel.Worksheet;       //这里读取的是第一个sheet,注意:这里第一个sheet的index为1
                    Excel.Range range = null;
                    if (sheet != null)
                        range = sheet.get_Range("A1");
                    string A1 = String.Empty;
                    if (range != null)
                        A1 = range.Text.ToString();
                    Color color1 = System.Drawing.ColorTranslator.FromOle(Convert.ToInt32(range.Font.Color));
                    Response.Write(string.Format("A1 value: {0} ForeColor:{1}", A1, color1.ToString()));    //输出A1的值和前景色
    
                    range = null;
                    if (sheet != null)
                        range = sheet.get_Range("A2");
                    string A2 = String.Empty;
                    if (range != null)
                        A2 = range.Text.ToString();
                    Color color2 = System.Drawing.ColorTranslator.FromOle(Convert.ToInt32(range.Interior.Color));
                    Response.Write(string.Format("A2 value: {0} Backcolor:{1}", A2, color2));        //输出A2的值和背景色
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
                finally
                {
                    if (wkb != null)
                    {
                        wkb.Close();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(wkb);
                    }
                    if (excel != null)
                    {
                        excel.Quit();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
                    }
                }

      原文地址:http://www.cnblogs.com/mib23/p/3777046.html

    转载请注明作者和原文链接,谢谢!

  • 相关阅读:
    如何选择开源许可证?(转)
    gdb的使用(转)
    git的使用
    2017-3-13 leetcode 4 11 15
    2017-3-12 leetcode 167 209 216
    2017-3-11 leetcode 217 219 228
    2017-3-10 leetcode 229 238 268
    1175: 零起点学算法82——find your present
    1174: 零起点学算法81——求整数绝对值
    1173: 零起点学算法80——求实数绝对值
  • 原文地址:https://www.cnblogs.com/mib23/p/3777046.html
Copyright © 2011-2022 走看看