4

我想编写一个程序,使用循环将文本框中的文本保存到 Excel 文件中,因为我想在 Excel 中插入多个文本。我找到了代码,但它只会覆盖单元格中的数据。我希望程序找到最后一行并将新数据插入下一行。我被困在这里,请有人帮助我如何在 C# 中做到这一点。

object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

xlWorkSheet.Cells[1, 1] = "FirstName";
xlWorkSheet.Cells[1, 2] = "LastName";
xlWorkSheet.Cells[1, 3] = "JobTitle";
xlWorkSheet.Cells[1, 4] = "Address";

for (int i=2; i<=6; i++)
{
    xlWorkSheet.Cells[i, 1] = textBox1.Text;
    xlWorkSheet.Cells[i, 2] = textBox2.Text;
    xlWorkSheet.Cells[i, 3] = textBox3.Text;
    xlWorkSheet.Cells[i, 4] = textBox4.Text;
}
4

2 回答 2

4

就像我提到的那样,您不需要使用循环。看这个例子

假设您的表单如下所示。

在此处输入图像描述

代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

Namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        Public Form1()
        {
            InitializeComponent();
        }

        //~~> Open File
        private void button1_Click(object sender, EventArgs e)
        {
            xlexcel = new Excel.Application();

            xlexcel.Visible = true;

            // Open a File
            xlWorkBook = xlexcel.Workbooks.Open("C:\\MyFile.xlsx", 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);

            xlWorkSheet.Cells[1, 1] = "FirstName";
            xlWorkSheet.Cells[1, 2] = "LastName";
            xlWorkSheet.Cells[1, 3] = "JobTitle";
            xlWorkSheet.Cells[1, 4] = "Address";
        }

        //~~> Add Data
        private void button2_Click(object sender, EventArgs e)
        {
            int _lastRow = xlWorkSheet.Range["A" + xlWorkSheet.Rows.Count].End[Excel.XlDirection.xlUp].Row + 1 ;

            xlWorkSheet.Cells[_lastRow, 1] = textBox1.Text;
            xlWorkSheet.Cells[_lastRow, 2] = textBox2.Text;
            xlWorkSheet.Cells[_lastRow, 3] = textBox3.Text;
            xlWorkSheet.Cells[_lastRow, 4] = textBox4.Text;
        }

        //~~> Once done close and quit Excel
        private void button3_Click(object sender, EventArgs e)
        {
            xlWorkBook.Close(true, misValue, misValue);
            xlexcel.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlexcel);
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}

评论跟进

Range 对象是工作表对象的一部分。所以你不应该在那里得到任何错误。就像我上面提到的,代码是经过试验和测试的。

在此处输入图像描述

更多跟进(来自评论)

上面的代码是在 VS 2010 Ultimate 上测试的。如果您有 VS 2008,则替换该行

int _lastRow = xlWorkSheet.Cells[xlWorkSheet.Rows.Count,
               1].End[Excel.XlDirection.xlUp].Row + 1;

int _lastRow = xlWorkSheet.Cells.Find(
                                      "*",
                                      xlWorkSheet.Cells[1,1],
                                      Excel.XlFindLookIn.xlFormulas,
                                      Excel.XlLookAt.xlPart,
                                      Excel.XlSearchOrder.xlByRows,
                                      Excel.XlSearchDirection.xlPrevious,
                                      misValue,
                                      misValue,
                                      misValue
                                      ).Row + 1 ;
于 2013-10-14T08:11:11.610 回答
0

你主要关心的是last used row在你的excel中找到。

为此,您可以使用

 Excel.Range usedRange = xlWorkSheet .UsedRange;
 Excel.Range _lastCell= usedRange.SpecialCells(Excel.XlCellType.xlCellTypeLastCell,  
 Type.Missing);

  int _lastRow= lastCell.Row; // Gives you the last used row in your Excel sheet
  int _lastCol = lastCell.Column; // Give you the last used column



 _lastRow++; // To get the next row 

    for (int i=_lastRow; i<=_lastrow+6; i++) // Set your i value to _lastRow
    {
        xlWorkSheet.Cells[i, 1] = textBox1.Text;
        xlWorkSheet.Cells[i, 2] = textBox2.Text;
        xlWorkSheet.Cells[i, 3] = textBox3.Text;
        xlWorkSheet.Cells[i, 4] = textBox4.Text;
    }
于 2013-10-14T05:42:07.460 回答