Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

asp.net - Writing Data to an Existing Excel File in C#

I want to write data to an existing Excel file, whilst preserving the original data.

The file has sheet1; I want to write on sheet2, then save. The problem is that every time I save, it will create a new Excel file and overwrite the existing one.

Could anyone provide any help to keep the old data while saving?

I have the following function

using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel; 

namespace WindowsApplication1
{
    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 ;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            MessageBox.Show(xlWorkSheet.get_Range("A1","A1").Value2.ToString());

            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

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

        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();
            }
        } 
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is my way to add data to existing excel file: (Its very simple and efficient)

1 - Add Microsoft.Office.Interop.Excel component as a reference to your application You can find it in .Net FrameWork in Extensions section

2- then add:

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

3- Now I have a simple class with 3 methods (openExcel, addDataToExcel, closeExcel)

public class ExcelFile
{

    private string excelFilePath = string.Empty;
    private int rowNumber = 1; // define first row number to enter data in excel

    Excel.Application myExcelApplication;
    Excel.Workbook myExcelWorkbook;
    Excel.Worksheet myExcelWorkSheet;

    public string ExcelFilePath
    {
        get { return excelFilePath; }
        set { excelFilePath = value; }
    }

    public int Rownumber
    {
        get { return rowNumber; }
        set { rowNumber = value; }
    }

    public void openExcel()
    {
        myExcelApplication = null;

        myExcelApplication = new Excel.Application(); // create Excell App
        myExcelApplication.DisplayAlerts = false; // turn off alerts


        myExcelWorkbook = (Excel.Workbook)(myExcelApplication.Workbooks._Open(excelFilePath, System.Reflection.Missing.Value,
           System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
           System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
           System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
           System.Reflection.Missing.Value, System.Reflection.Missing.Value)); // open the existing excel file

        int numberOfWorkbooks = myExcelApplication.Workbooks.Count; // get number of workbooks (optional)

        myExcelWorkSheet = (Excel.Worksheet)myExcelWorkbook.Worksheets[1]; // define in which worksheet, do you want to add data
        myExcelWorkSheet.Name = "WorkSheet 1"; // define a name for the worksheet (optinal)

        int numberOfSheets = myExcelWorkbook.Worksheets.Count; // get number of worksheets (optional)
    }

    public void addDataToExcel(string firstname, string lastname, string language, string email, string company)
    {

        myExcelWorkSheet.Cells[rowNumber, "H"] = firstname;
        myExcelWorkSheet.Cells[rowNumber, "J"] = lastname;
        myExcelWorkSheet.Cells[rowNumber, "Q"] = language;
        myExcelWorkSheet.Cells[rowNumber, "BH"] = email;
        myExcelWorkSheet.Cells[rowNumber, "CH"] = company;
        rowNumber++;  // if you put this method inside a loop, you should increase rownumber by one or wat ever is your logic

    }

    public void closeExcel()
    {
        try
        {
            myExcelWorkbook.SaveAs(excelFilePath, 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); // Save data in excel


            myExcelWorkbook.Close(true, excelFilePath, System.Reflection.Missing.Value); // close the worksheet


        }
        finally
        {
            if (myExcelApplication != null)
            {
                myExcelApplication.Quit(); // close the excel application
            }
        }

    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...