【问题标题】:Is if possible to use c# to access excel files? [duplicate]是否可以使用 c# 访问 excel 文件? [复制]
【发布时间】:2013-05-03 10:33:17
【问题描述】:

您好,问题很简单,我想进入文件夹查找 excel 文件。然后进入每个excel文件并使用c#将红色字体颜色更改为黑色。这可能吗?

namespace Excel_font_color_change
{
    public partial class Form1 : Form
    {
        public Form1()
        {

            InitializeComponent();
        }



        private void button1_Click(object sender, EventArgs e)
        {
            List<string> HtmlPathList = new List<string>();
            string folderToSearch;

            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = true;//allow user to create new folders through this dialog
            fbd.RootFolder = Environment.SpecialFolder.MyDocuments;//defaults to my computer
            System.Windows.Forms.DialogResult dr = fbd.ShowDialog();//make sure user clicks ok
            if (dr == DialogResult.OK)
            {
                folderToSearch = fbd.SelectedPath;//gets folder path
                try
                {
                    var allFiles = from files in Directory.EnumerateFiles(folderToSearch, "*.xls*", SearchOption.AllDirectories)
                                   select Path.GetFullPath(files);//gets all files with htm & htm + something for extensions
                    foreach (string filepath in allFiles)
                    {
                        HtmlPathList.Add(filepath);//adds each filepath found to the list
                    }
                }
                catch (UnauthorizedAccessException UAEx) { Console.WriteLine(UAEx.Message); }//error handling
                catch (PathTooLongException PathEx) { Console.WriteLine(PathEx.Message); }//error handling
                Console.WriteLine("1");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

        }
    }

这是我到目前为止所拥有的,我希望第二个按钮采用HtmlPathList 中的文件路径,如果字体颜色为红色,则将其编辑为黑色。我现在正在通过How to read data of an Excel file using C#? 寻找。

【问题讨论】:

  • 是的,有可能。
  • 是的。到目前为止你走了多远?您可以枚举目录中的文件,然后使用 EPPlus 之类的工具打开和修改 Excel 文件。
  • 一切皆有可能......解放你的思想
  • @TimSchmelter 您应该将其添加为答案,因为问题是 这可能吗? -_-
  • 如果您不想/安装 Office,请查看 Open XML。

标签: c# excel


【解决方案1】:

查看这个库。它只适用于 xlsx。

http://www.microsoft.com/en-us/download/details.aspx?id=5124

如果您想读取旧的 xls 文件,您可以使用 Interop 程序集。

http://www.microsoft.com/en-us/download/details.aspx?id=3508

【讨论】:

    【解决方案2】:

    此解决方案需要引用 Excel 互操作程序集(Excel 必须安装在执行实用程序的计算机上,因为互操作程序集在后台执行 excel):

        using Microsoft.Office.Interop.Excel;
    
        /// <summary>
        /// sets a cell range's font color
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="startCell"></param>
        /// <param name="endCell"></param>
        /// <param name="color"></param>
        public void setCellRangeFontColor(string filename, string startCell, string endCell, string color)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
    
            if (xlApp == null)
            {
                MessageBox.Show("EXCEL could not be started. Check that your office installation and project references are correct.");
                return;
            }
            //xlApp.Visible = true;
    
            //Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Workbook wb = xlApp.Workbooks.Open(filename,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing);
            Worksheet ws = (Worksheet)wb.Worksheets[1];
    
            if (ws == null)
            {
                MessageBox.Show("Worksheet could not be created. Check that your office installation and project references are correct.");
            }
    
            ws.get_Range(startCell, endCell).Font.Color = System.Drawing.ColorTranslator.ToOle(Color.FromName(color));
    
            wb.Close(true, Type.Missing, Type.Missing);
    
            //wb.Save();
            xlApp.Quit();
    
            releaseObject(ws);
            releaseObject(wb);
            releaseObject(xlApp);
        }
    
        public static void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                //MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      相关资源
      最近更新 更多