使用C#填充Excel表格

5
我在程序结构方面出现了问题。每次我在Windows表单应用程序中按下按钮时,我的Excel工作表都应该更新一个单元格中的数据。
以下是我的代码:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace Test6attendance
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {


        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;

        if (File.Exists("D:\\login.xlscsharp-Excel.xls"))
        {

            object misValue = System.Reflection.Missing.Value;
            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Open("D:\\login.xlscsharp-Excel.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            for (int i = 1; i < 55555; i++)
            {


                if (xlWorkSheet.Cells[i, 1] == null)
                {

                    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                    xlWorkSheet.Cells[i, 1] = DateTime.Now.ToString("MM/dd/ yyyy, hh:mm:ss tt");
                    xlWorkBook.SaveAs("D:\\login.xlscsharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                    xlWorkBook.Close(true, misValue, misValue);
                    xlApp.Quit();

                    releaseObject(xlWorkSheet);
                    releaseObject(xlWorkBook);
                    releaseObject(xlApp);

                    MessageBox.Show("Excel file updated , you can find the file D:\\csharp-Excel.xls");

                }

            }



        }
        else
        {

            //Create New Code



            object misValue = System.Reflection.Missing.Value;


            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);




            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            xlWorkSheet.Cells[1, 1] = DateTime.Now.ToString("MM/dd/ yyyy, hh:mm:ss tt");


            xlWorkBook.SaveAs("D:\\login.xlscsharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            MessageBox.Show("Excel file created , you can find the file D:\\csharp-Excel.xls");

        }
    }
         private 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();
        }
    }

    private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {

    }
    }


}

我认为问题出在for循环上,它似乎无法正常工作。需要一些建议或参考来解决它。


你应该将 xlWorkBook.Worksheets 保存为一个单独的变量,否则你就没有完全清理所有使用过的对象。 - rhughes
此外,值得将您的代码放入 try/catch 中,并在 finally 中进行清理,以避免任何对象泄漏的风险。 - rhughes
怎么做呢?我正在尝试,但是没有保存xlWorkBook.Worksheets的选项,只有SaveAs可用,而且我使用它时出现了错误。 - user3640620
2个回答

0

问题出在

if (xlWorkSheet.Cells[i, 1] == null)

应该是这样的

 if (xlWorkSheet.Cells[i, 1] == null)

由于您的第一个if条件检查文件是否存在if (File.Exists("D:\\login.xlscsharp-Excel.xls")),如果不存在,则创建一个文件并将值分配给cell [1,1]。现在,当您第二次单击时,该单元格不为空,您的值不会得到更新。

尝试使用此代码

for (int i = 1; i < 55555; i++)
            {


                if (xlWorkSheet.Cells[i, 1] != null)
                {

                    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                    xlWorkSheet.Cells[i, 1] = DateTime.Now.ToString("MM/dd/ yyyy, hh:mm:ss tt");
                    xlWorkBook.SaveAs("D:\\login.xlscsharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                    xlWorkBook.Close(true, misValue, misValue);
                    xlApp.Quit();

                    releaseObject(xlWorkSheet);
                    releaseObject(xlWorkBook);
                    releaseObject(xlApp);

                    MessageBox.Show("Excel file updated , you can find the file D:\\csharp-Excel.xls");
                    break;

                }

            }

现在我收到了一个消息,要求我替换现有的文件,并给出了以下消息:“在Test6attendance.exe中发生了未处理的类型为'System.Runtime.InteropServices.COMException'的异常附加信息:来自HRESULT的异常:0x800A03EC” - user3640620
代码必须替换现有单元格中的数据,如果前一个单元格有一些值,它应该检查下一个单元格是否为空,只有在它为空时才应该写入值。如果文件已经存在,则应该更新它而不更改先前的条目。新值应该输入到下一个空白单元格中。 - user3640620
如果我使用if(xlWorkSheet.Cells[i, 1] != null) 而不是if(xlWorkSheet.Cells[i, 1] != null)我该如何完成我的任务? - user3640620
如果您想在下一个空单元格中输入值,则应使用 if (xlWorkSheet.Cells[i, 1] == null)。请更新我的答案,再试一次。 - Sid M
1
尝试使用Save()而不是SaveAs()。 SaveAs()需要另一个文件名。还请检查我的下面的答案。 - Mitja Bezenšek
显示剩余5条评论

0
你的循环非常奇怪。你应该把循环中的所有代码放在循环外面,只保留赋值变量的那一行在循环内部。否则你会为每行保存一次应用程序。更不用说,在赋第一个值之后你就释放了所有对象。我猜测只能写入一个值,然后在循环的第一行引发很多异常(你试图从一个已释放的工作簿对象获取工作表)。应该像这样:
for (int i = 1; i < 55555; i++)
{
   if (xlWorkSheet.Cells[i, 1] != null)
   {
       xlWorkSheet.Cells[i, 1] = DateTime.Now.ToString("MM/dd/ yyyy, hh:mm:ss tt"); 
   }
}
xlWorkBook.Save("D:\\login.xlscsharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file updated , you can find the file D:\\csharp-Excel.xls");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接