Warm tip: This article is reproduced from serverfault.com, please click

其他-使用C#写入Excel。

(其他 - Write to Excel using C#. ( function that will enter one value into an excel every time its called))

发布于 2020-11-28 01:30:53

我需要编写将使用C#在Excel中的单元格中输入一个字符串的函数的帮助。我遇到的问题是,当我尝试使用计数器来确保工作表仅在一次出现错误时创建。如果我那里没有if语句,那么代码将制作大量工作表,并且仅将最后一个数据点保存在等于Excelcounter值的单元格中。

      public void WriteSample()
        {
            Excel.Application excelApp = new Excel.Application();
            if (excelApp != null)
            {
                if (Excelcounter == 0) // data_count keeps track of how many operations i have made to excel
                {
                    Excel.Workbook excelWorkbook = excelApp.Workbooks.Add(); // Initalize the excell sheet
                    Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets.Add();
                }
                    Excelcounter++; // increment
                
// in the lines below anything that has to with the variable "excelWorkbook" and "excelWorksheet' will give an error 
                excelWorksheet.Cells[Excelcounter, 1] = str4; // add data to excel (this is where i am getting my error)
                

                excelWorkbook.Close(); // close Excel 
                excelApp.Quit();

                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelWorksheet);
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelWorkbook);
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelApp);
                GC.Collect();
                GC.WaitForPendingFinalizers();

            }
        }

我知道我得到错误的原因是因为变量与它们的接口分开(不确定接口是否是正确的术语)。我是C#的新手,这只是我使用该语言的第二个项目。有没有一种方法可以继续使用上面代码中的逻辑而无需添加大量代码(这可能会使我更加困惑)?非常感谢你们!!

Questioner
prenixd
Viewed
22
user9938 2020-11-29 06:10:38

请尝试以下方法:

添加对Microsoft.Excel对象库的引用(例如:Microsoft.Excel 16.0对象库)

  • 在菜单上,单击项目
  • 选择添加参考
  • 选择COM
  • 选择Microsoft.Excel xx.x对象库(例如:Microsoft.Excel 16.0对象库)

添加以下using语句:

using System.IO;
using System.Diagnostics;
using Excel = Microsoft.Office.Interop.Excel;

选项1:

如果要设置一个按行引用该单元格的字符串值,请执行以下操作:

public void ExcelWriteValue(string filename, int rowNum, int colNum, string dataValue, string worksheetName = "")
{
    //Write cell value using row number and column number

    //*Note: Excel cells, can also be referenced by name, such as "B2"
    //
    //       All indices in Excel (rowNumber, columnNumber, etc...) start with 1 
    //       The format is: <rowNumber>, <columnNumber>
    //       The top left-most column, is: 1,1



    bool specifiedWorksheetFound = false;
    object oMissing = System.Reflection.Missing.Value;

    Excel.Application excelApp = null;
    Excel.Worksheet previousActiveSheet = null;
    Excel.Range range = null;
    Excel.Workbook workbook = null;
    Excel.Worksheet worksheet = null;
    
    //keep track of existing worksheet names
    SortedDictionary<string, bool> worksheetDict = new SortedDictionary<string, bool>();

    int worksheetCount = 0;

    try
    {

        //create new instance
        excelApp = new Excel.Application();

        //suppress displaying alerts (such as prompting to overwrite existing file)
        excelApp.DisplayAlerts = false;

        //set Excel visability
        excelApp.Visible = false;

        //if writing/updating a large amount of data
        //disable screen updating by setting value to false
        //for better performance.
        //re-enable when done writing/updating data, if desired
        //excelApp.ScreenUpdating = false;


        if (excelApp != null)
        {
            if (File.Exists(filename))
            {
                System.Diagnostics.Debug.WriteLine("'" + filename + "' exists. Existing file will be modified.");

                //open existing Excel file
                workbook = excelApp.Workbooks.Open(filename);

                //get number of existing worksheets
                worksheetCount = workbook.Sheets.Count;

                if (worksheetCount >= 1)
                {
                    foreach (Excel.Worksheet ws in workbook.Sheets)
                    {
                        //System.Diagnostics.Debug.WriteLine("worksheet name: '" + ws.Name + "'");

                        if (!String.IsNullOrEmpty(worksheetName) && ws.Name == worksheetName)
                        {
                            //set value to desired/specified worksheet
                            worksheet = ws;

                            //set value
                            specifiedWorksheetFound = true;
                        }

                        if (!worksheetDict.ContainsKey(ws.Name))
                        {
                            //add worksheet name to dictionary
                            //the bool value isn't used, so it's value isn't important
                            //it exists because a Dictionary requires both a key and a value
                            worksheetDict.Add(ws.Name, true);
                        }
                    }

                    if (!String.IsNullOrEmpty(worksheetName) && !specifiedWorksheetFound)
                    {
                        //specified worksheet not found

                        System.Windows.Forms.MessageBox.Show("Error: Worksheet '" + worksheetName + "' not found in filename '" + filename + "'.", "Error - Worksheet Not Found", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        return;
                    }
                    else if (!String.IsNullOrEmpty(worksheetName) && specifiedWorksheetFound)
                    {
                        //set value 
                        previousActiveSheet = excelApp.ActiveSheet;

                        //specified worksheet found
                        //activate desired worksheet
                        worksheet.Activate();
                    }
                    else
                    {
                        //set value 
                        previousActiveSheet = excelApp.ActiveSheet;

                        //no worksheet name specified
                        //default to 1st worksheet
                        worksheet = workbook.Sheets[1];

                        //active worksheet
                        worksheet.Activate();
                    }
                }
                else
                {
                    //no worksheets exist
                    //add a worksheet and set the value to the new worksheet
                    worksheet = workbook.Sheets.Add();
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("'" + filename + "' doesn't exit. Creating new workbook.");

                //create new workbook
                workbook = excelApp.Workbooks.Add();

                //get number of existing worksheets
                worksheetCount = workbook.Sheets.Count;

                //add a worksheet and set the value to the new worksheet
                worksheet = workbook.Sheets.Add();

            }


            //set cell location that data needs to be written to
            //range = worksheet.Cells[rowNum, colNum];

            //set value of cell
            //range.Value = dataValue;

            //set value of cell
            worksheet.Cells[rowNum, colNum] = dataValue;

            System.Diagnostics.Debug.WriteLine("Info: Value for cell " + rowNum + "," + colNum + " in worksheet '" + worksheet.Name + "' set.");

            if (previousActiveSheet != null)
            {
                //restore active sheet to one that was previously the active sheet
                //so that when the user opens the workbook, it will open to the last sheet he/she opened
                worksheet = previousActiveSheet;
                worksheet.Activate();
            }

            //save Workbook - if file exists, overwrite it
            workbook.SaveAs(filename, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);

            System.Diagnostics.Debug.WriteLine("Status: Complete. " + DateTime.Now.ToString("HH:mm:ss"));
        }
    }
    catch (Exception ex)
    {
        string errMsg = "Error: ExcelWriteValue - " + ex.Message;
        System.Diagnostics.Debug.WriteLine(errMsg);

        if (ex.Message.StartsWith("Cannot access read-only document"))
        {
            System.Windows.Forms.MessageBox.Show(ex.Message + "Please close the workbook, before trying again.", "Error - Unable To Write To Workbook", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
        }
    }
    finally
    {
        if (workbook != null)
        {
            //set value
            range = null;
            previousActiveSheet = null;
            worksheet = null;

            //close workbook
            workbook.Close();

            //release all resources
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
        }

        if (excelApp != null)
        {
            //close Excel
            excelApp.Quit();

            //release all resources
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelApp);
        }
    }
}

*注意:未使用SortedDictionary。我添加了它,以防你需要跟踪现有的工作表名称。

选项2:

如果要设置一个通过名称引用单元格的字符串值(例如:“ B2”):

public void ExcelWriteValue(string filename, string cellName, string dataValue, string worksheetName = "")
{
    //Write cell value using the Excel cell name (ex: B2)

    //*Note: Excel cells, can also be referenced by row,column such as "1,2"
    //
    //       All indices in Excel (rowNumber, columnNumber, etc...) start with 1 
    //       The format is: <rowNumber>, <columnNumber>
    //       The top left-most column, is: 1,1



    bool specifiedWorksheetFound = false;
    object oMissing = System.Reflection.Missing.Value;

    Excel.Application excelApp = null;
    Excel.Worksheet previousActiveSheet = null;
    Excel.Range range = null;
    Excel.Workbook workbook = null;
    Excel.Worksheet worksheet = null;

    //keep track of existing worksheet names
    SortedDictionary<string, bool> worksheetDict = new SortedDictionary<string, bool>();

    int worksheetCount = 0;

    try
    {

        //create new instance
        excelApp = new Excel.Application();

        //suppress displaying alerts (such as prompting to overwrite existing file)
        excelApp.DisplayAlerts = false;

        //set Excel visability
        excelApp.Visible = false;


        //if writing/updating a large amount of data
        //disable screen updating by setting value to false
        //for better performance.
        //re-enable when done writing/updating data, if desired
        //excelApp.ScreenUpdating = false;


        if (excelApp != null)
        {
            if (File.Exists(filename))
            {
                System.Diagnostics.Debug.WriteLine("'" + filename + "' exists. Existing file will be modified.");

                //open existing Excel file
                workbook = excelApp.Workbooks.Open(filename);

                //get number of existing worksheets
                worksheetCount = workbook.Sheets.Count;

                if (worksheetCount >= 1)
                {
                    foreach (Excel.Worksheet ws in workbook.Sheets)
                    {
                        //System.Diagnostics.Debug.WriteLine("worksheet name: '" + ws.Name + "'");

                        if (!String.IsNullOrEmpty(worksheetName) && ws.Name == worksheetName)
                        {
                            //set value to desired/specified worksheet
                            worksheet = ws;

                            //set value
                            specifiedWorksheetFound = true;
                        }

                        if (!worksheetDict.ContainsKey(ws.Name))
                        {
                            //add worksheet name to dictionary
                            //the bool value isn't used, so it's value isn't important
                            //it exists because a Dictionary requires both a key and a value
                            worksheetDict.Add(ws.Name, true);
                        }
                    }

                    if (!String.IsNullOrEmpty(worksheetName) && !specifiedWorksheetFound)
                    {
                        //specified worksheet not found

                        System.Windows.Forms.MessageBox.Show("Worksheet '" + worksheetName + "' not found in filename '" + filename + "'.", "Error - Worksheet Not Found", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        return;
                    }
                    else if (!String.IsNullOrEmpty(worksheetName) && specifiedWorksheetFound)
                    {
                        //set value 
                        previousActiveSheet = excelApp.ActiveSheet;

                        //specified worksheet found
                        //activate desired worksheet
                        worksheet.Activate();
                    }
                    else
                    {
                        //set value 
                        previousActiveSheet = excelApp.ActiveSheet;

                        //no worksheet name specified
                        //default to 1st worksheet
                        worksheet = workbook.Sheets[1];

                        //active worksheet
                        worksheet.Activate();
                    }
                }
                else
                {
                    //no worksheets exist
                    //add a worksheet and set the value to the new worksheet
                    worksheet = workbook.Sheets.Add();
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("'" + filename + "' doesn't exit. Creating new workbook.");

                //create new workbook
                workbook = excelApp.Workbooks.Add();

                //get number of existing worksheets
                worksheetCount = workbook.Sheets.Count;

                //add a worksheet and set the value to the new worksheet
                worksheet = workbook.Sheets.Add();

            }

            

            //set cell location that data needs to be written to
            //range = worksheet.Range[cellName];

            //set value of cell
            //range.Value = dataValue;

            //set value of cell
            worksheet.Range[cellName].Value = dataValue;

            System.Diagnostics.Debug.WriteLine("Info: Value for cell " + cellName + " in worksheet '" + worksheet.Name + "' set.");

            if (previousActiveSheet != null)
            {
                //restore active sheet to one that was previously the active sheet
                //so that when the user opens the workbook, it will open to the last sheet he/she opened
                worksheet = previousActiveSheet;
                worksheet.Activate();
            }

            //save Workbook - if file exists, overwrite it
            workbook.SaveAs(filename, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);

            System.Diagnostics.Debug.WriteLine("Status: Complete. " + DateTime.Now.ToString("HH:mm:ss"));
        }
    }
    catch (Exception ex)
    {
        string errMsg = "Error: ExcelWriteValue - " + ex.Message;
        System.Diagnostics.Debug.WriteLine(errMsg);

        if (ex.Message.StartsWith("Cannot access read-only document"))
        {
            System.Windows.Forms.MessageBox.Show(ex.Message + "Please close the workbook, before trying again.", "Error - Unable To Write To Workbook", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
        }
    }
    finally
    {
        if (workbook != null)
        {
            //set value
            range = null;
            previousActiveSheet = null;
            worksheet = null;

            //close workbook
            workbook.Close();

            //release all resources
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
        }

        if (excelApp != null)
        {
            //close Excel
            excelApp.Quit();

            //release all resources
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelApp);
        }
    }
}

*注意:未使用SortedDictionary。我添加了它,以防你需要跟踪现有的工作表名称。

如果这有帮助,请将其标记为答案。