【问题标题】:Is it possible to write to an existing Excel file when it is **open** on the desktop?是否可以在桌面上**打开**时写入现有的 Excel 文件?
【发布时间】:2017-07-18 09:36:03
【问题描述】:

我想创建一个将数据写入现有 Excel 文件的代码。只有当文件关闭时,它才会读/写文件。如果我在桌面上打开文件时尝试写入文件,它不会更改或保存文档。在代码运行之前或期间打开 Excel 文件时,我也无法关闭工作簿(使用 .close())或退出应用程序(使用 .quit())。

有没有一种方法可以在我的桌面上打开一个 Excel 文件并实际显示更改?或者我可以至少关闭一个已经打开的文件读/写它,保存它并用 C# 代码再次打开它?这是我正在使用的代码;它有点杂乱无章,但如果你运行它,你可以看到我本质上想要做的事情。请注意,您必须更改要保存文件的属地址才能使代码正常工作(通用地址保存为名为 excelsource 的字符串变量)。该代码将首先创建一个以今天的月份和日期 (MM_YY) 命名的文件。每次初始化代码时,它都会继续写入。如果您在新创建的文件打开时尝试写入文件,则不会对文件应用任何更改(仅在文件关闭时写入 excel 文件)。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Diagnostics;
using System.Threading;

namespace ConsoleApplication4
{
class Program
{
    static public string excelsource = @"\user\desktop\generic\";
    // excelsource is the "general" address of where excel file wil be saved.
    static public bool truth;
    static public bool truth1;
    static public bool scan_thru = false;
    static public int range2;
    static public int index = 1;
    static Excel.Application excel = new Excel.Application();
    static Excel.Workbook workbook;
    static Excel.Worksheet sheet;
    static Excel.Range range;
    static FileInfo file;

    static void Main(string[] args)
    {
        DateTime current_time = DateTime.Now;
        string file_name = excelsource + current_time.Month.ToString() + "_" + current_time.Year.ToString() + ".xlsx";
        string curfile = file_name;
        truth = File.Exists(curfile);
        // truth determines if file exists if truth == true file exists and does not need to be created, if false a new file is created.
        if (truth == false)
        {
            workbook = excel.Workbooks.Add();
            sheet = workbook.Sheets[1];
            sheet.Name = (current_time.Month.ToString() + "_" + current_time.Day + "_" + current_time.Year);
        }
        else
        {
            file = new FileInfo(file_name);
            truth1 = IsFileinUse(file);
            // truth1 determines if the existing file is open; truth1 == false if the file is currently closed and is true when it is open.
            workbook = excel.Workbooks.Open(file_name);
            sheet = workbook.Sheets[current_time.Month.ToString() + "_" + current_time.Day + "_" + current_time.Year];
            if (truth1 == true)
            {
                excel.Visible = false;
                excel.DisplayAlerts = false;
                workbook.Save();
            }
            while (scan_thru == false & truth1 == false)
                {
                string box = "A" + index.ToString();
                    range = sheet.get_Range(box, Missing.Value);
                    string range1 = range.Text;
                    bool judge = int.TryParse(range1, out range2);
                    if (judge == true)
                    {
                        index++;
                    }
                    else
                    {
                        scan_thru = true;
                    }
                }
                scan_thru = false;

        }
            int i = index;
            while (i < (index + 100) & truth1 == false)
            {
                sheet.Cells[i, "A"].Value2 = i.ToString();                   
                i++;
            }


            if (truth == false)
            {
                workbook.SaveAs(file_name);
            }
            if (truth == true & truth1 == false)
            {
                excel.DisplayAlerts = false;
            }
            index = 1;
            workbook.Close(true);
            excel.Quit();

    }
    protected static bool IsFileinUse(FileInfo file)
    {
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            return true;
        }
        finally
        {
           if (stream != null)
                stream.Close();
        }
        return false;
    }

}

}

【问题讨论】:

    标签: c# excel


    【解决方案1】:

    这个帖子太老了。但我面临同样的问题。我想写一个 .csv 文件,而它在桌面上从外部打开。这个问题是 Excel 锁定文件以使其在读/写模式下使用,因此我的应用程序抛出 "File already in Use Error" 。因此,为了解决这个问题,当在桌面上从外部访问文件时,必须以只读模式打开文件。如果您从应用程序创建 .csv 文件,请在只读模式下创建它。并且当您想在其上写入时,将其转换为该实例的读写模式,并在写入后将其转换回只读。因此,您可以在显示所有数据的后台保持 .csv 文件打开。但是,它必须重新打开以获取您在后台打开时可能已写入文件的更新数据。 我用来转换为读/写和只读的代码:

    // Convert to Read-Write
    File.SetAttributes(FileName, File.GetAttributes(FileName) & ~FileAttributes.ReadOnly);                
    // Write to the .csv File
    // Convert back to Read only
    File.SetAttributes(FileName, System.IO.FileAttributes.ReadOnly);
    

    【讨论】:

    • 一般来说,这可能是一个合适的过程,可确保您获得写访问权限,它不能直接回答问题,即是否可以在 Excel 文件打开时更新它 并实时反映变化。
    【解决方案2】:

    这很有可能在 C# 应用程序中是不可能做到的。在 Excel 中打开文件时,它会阻止来自其他应用程序的写入访问,以维护打开文件中的数据完整性。这意味着您应该具有只读访问权限。

    此外,从外部应用程序强制打开和关闭任何应用程序是非常非常少见的更新文件的最佳方法。如果您想从当前打开的文件中修改数据,您应该学习学习编写 Excel 宏。

    编辑1:澄清问题后:

    您无法添加到打开的 Excel 文件中。但是,如果我正确理解您的问题,我认为这将解决您的问题(我试过了,它对我有用):

    1. 写入一个逗号分隔的 .csv 文件,您可以控制从 C# 应用程序对它的读/写访问。
    2. 在引用 .csv 文件的 Excel 电子表格“来自文本”中添加“外部数据源”。来源:https://support.office.com/en-us/article/Import-or-export-text-txt-or-csv-files-5250ac4c-663c-47ce-937b-339e391393ba 在“通过连接导入文本文件”部分下。
    3. 在“数据”选项卡的“连接”标题下,您希望更改“属性”以每隔一段时间或在打开文件时刷新。如果您不会每次都更改文件名,我会取消选中“刷新时提示输入文件名”框。

    希望这对你有用。如果您需要更多说明,请再次评论。

    【讨论】:

    • 我真的很想使用 Excel 宏,但是我正在从传感器收集数据并通过 MODBUS tcp/以太网传输 plc 收集的数据。我有一个库可以在我的电脑和我的 plc 之间为我执行 Modbus 通信,但是它只适用于 C# 语言。因此我需要使用 C# 作为中间人。我真的只需要 Excel 来存储一天中收集的数据并将其显示到图表中。我知道 Visual Basic 可以创建图表,但它无法显示我要收集的所有数据。
    • 谢谢,这可能会很有帮助。我将在今天晚些时候对此进行调查。
    • 很抱歉打扰你,但你能引导我到一个网站,其中给出了如何在 C# 中创建 CVS 文件的逐步分解。
    • 最简单的方法是创建一个文件,并将其写入一个格式化字符串的文件。这里有一些链接...stackoverflow.com/questions/18757097/writing-data-into-csv-filestackoverflow.com/questions/7569904/…stackoverflow.com/questions/5516870/…
    • 这种技术只是将锁定文件冲突的可能性从工作簿文件转移到 csv 文件。诚然,发生冲突的可能性降低了,但并未消除。当我对其进行测试时,如果另一个应用程序在尝试刷新数据时打开了 csv,则 Excel 会崩溃。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2022-08-02
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多