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

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

  • 相关阅读:
    统计学——平均数
    JSON与JAVA的数据转换
    Linux使用笔记
    vim代码折叠命令
    让ubuntu的ssh保持长时间连接
    Ubuntu通过xinput禁用及启用联想笔记本的触摸板
    linux下Oracle 相关命令
    linux机械磁盘服务器分区方案
    centos 6.5搭建LNMP环境
    centos6.5下搭建oracle 11g
  • 原文地址:https://www.cnblogs.com/mib23/p/3777046.html
Copyright © 2011-2022 走看看