【问题标题】:Writing Data to an Existing Excel File in C#在 C# 中将数据写入现有 Excel 文件
【发布时间】:2014-02-09 12:33:26
【问题描述】:

我想将数据写入现有 Excel 文件,同时保留原始数据。

文件有sheet1;我想在sheet2上写,然后保存。 问题是每次我保存时,它都会创建一个新的 Excel 文件并覆盖现有的文件。

任何人都可以提供任何帮助以在保存时保留旧数据吗?

我有以下功能

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, "\t", 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();
            }
        } 
    }
}

【问题讨论】:

  • 你能贴出你试过的代码吗?
  • 我刚刚编辑了问题。

标签: c# asp.net excel


【解决方案1】:

这是我将数据添加到现有 excel 文件的方法:(非常简单高效)

1 - 添加 Microsoft.Office.Interop.Excel 组件作为对您的应用程序的引用 您可以在扩展部分的 .Net FrameWork 中找到它

2- 然后添加:

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

3- 现在我有一个简单的类,有 3 个方法(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
            }
        }

    }
}

【讨论】:

    【解决方案2】:

    根据Programmatically Insert to Existing Excel File using C# by R Manimaran

    这是插入已存在的 excel 文件的代码。

    private static Microsoft.Office.Interop.Excel.Workbook mWorkBook;
    private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
    private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1;
    private static Microsoft.Office.Interop.Excel.Application oXL;
    public static void ReadExistingExcel()
    {
       string path = @"C:\Tool\Reports1.xls";
       oXL = new Microsoft.Office.Interop.Excel.Application();
       oXL.Visible = true;
       oXL.DisplayAlerts = false;
       mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
       //Get all the sheets in the workbook
      mWorkSheets = mWorkBook.Worksheets;
       //Get the allready exists sheet
       mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Sheet1");
       Microsoft.Office.Interop.Excel.Range range= mWSheet1.UsedRange;
       int colCount = range.Columns.Count;
       int rowCount= range.Rows.Count;
       for (int index = 1; index < 15; index++)
       {
          mWSheet1.Cells[rowCount + index, 1] = rowCount +index;
          mWSheet1.Cells[rowCount + index, 2] = "New Item"+index;
       }
       mWorkBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
       Missing.Value, Missing.Value, Missing.Value,    Missing.Value,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
       Missing.Value, Missing.Value, Missing.Value,
       Missing.Value, Missing.Value);
       mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
       mWSheet1 = null;
       mWorkBook = null;
       oXL.Quit();
       GC.WaitForPendingFinalizers();
       GC.Collect();
       GC.WaitForPendingFinalizers();
       GC.Collect();
    } 
    

    如果您需要创建新工作表,请使用以下代码。

    oSheet = (Excel.Worksheet)oWB.Sheets.Add(Missing.Value, Missing.Value, Missing.Value,      Missing.Value);
    
    oSheet.Name = SheetName;
    

    【讨论】:

    • 它不起作用。它仍然创建新文件,并覆盖现有文件
    【解决方案3】:

    在我的情况下使用 ClosedXml dll 解决了我的问题

     var workbook = new XLWorkbook(fileName);
      var ws1 = workbook.Worksheet(1);
      var ws2 = workbook.Worksheet(2);
      workBook.SaveAs(fileName);
    

    这是我的代码:

    public void ExcelDataAssign(List<string> ColumnwiseData, int length, DateTime ReportDate, List<string> AmountList, List<string> PeriodDateList, int CellId)
        {
            int PeriodColIndex = 6, Desc1ColIndex = 14, Desc2ColIndex = 11, Desc3ColIndex = 9, PeriodDateColIndex = 7;
            int PeriodRowIndex = 3, Desc1RowIndex = 1, Desc2RowIndex = 1, Desc3RowIndex = 1, PeriodDateRowIndex = 3;
    
    
            string cellName = ColumnwiseData[length];
            string CapitiveName = ColumnwiseData[2 * length];
            string DomicileName = ColumnwiseData[3 * length];
    
    
            string file = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\Excel\OutputTemplate.xlsx";
            string fileName = file.Replace("bin", "").Replace("Debug", "");
            var workbook = new XLWorkbook(fileName);
            var ws1 = workbook.Worksheet(1);
    
            ws1.Cell(1, 2).Value = DomicileName;
            ws1.Cell(2, 2).Value = CapitiveName;
            ws1.Cell(3, 2).Value = cellName;
            ws1.Cell(4, 2).Value = ReportDate;
    
            int amntIncr = 0;
            while (AmountList.Count > amntIncr)
            {
                ws1.Cell(PeriodColIndex, PeriodRowIndex).Value = "Period";
                ws1.Cell(Desc1ColIndex, Desc1RowIndex + 2).Value = AmountList[amntIncr];
                ws1.Cell(Desc2ColIndex, Desc2RowIndex + 2).Value = (AmountList[amntIncr + 1]);
                ws1.Cell(Desc3ColIndex, Desc3RowIndex + 2).Value = (AmountList[amntIncr + 2]);
                PeriodRowIndex++;
                Desc1RowIndex++;
                Desc2RowIndex++;
                Desc3RowIndex++;
                amntIncr = amntIncr + 3;
    
            }
            int periodDateIncr = 0;
            while (PeriodDateList.Count > periodDateIncr)
            {
                ws1.Cell(PeriodDateColIndex, PeriodDateRowIndex).Value = PeriodDateList[periodDateIncr];
                PeriodDateRowIndex++;
                periodDateIncr = periodDateIncr + 3;
            }
    
            var ws2 = workbook.Worksheet(2);
            ws2.Cell(1, 2).Value = DomicileName;
            ws2.Cell(2, 2).Value = CapitiveName;
            ws2.Cell(3, 2).Value = cellName;
            ws2.Cell(4, 2).Value = ReportDate;
    
    
            SqlParameter paramCellId = new SqlParameter("@CellId", CellId);
            SqlParameter paramReportDate = new SqlParameter("@ReportDate", ReportDate);
            DataTable dt = new DataTable();
            var data = SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, "Usp_inputResult", paramCellId, paramReportDate).Tables[0];
    
    
            List<string> lstClmwiseData = new List<string>();
    
            foreach (DataRow r in data.Rows)
            {
                foreach (DataColumn c in data.Columns)
                {
                    lstClmwiseData.Add(r[c].ToString());
                }
            }
    
            int snoColIndex = 6, GLCodeColIndex = 6, DescriptioColIndex = 6, movementDebitColIndex = 6, movementCreditColIndex = 6, ClosingdebitcolIndex = 6, ClosingCreditColIndex = 6;
            int snoRowIndex = 1, GLCodRowIndex = 2, DescriptioRowIndex = 3, movementDebitRowIndex = 4, movementCreditRowIndex = 5, ClosingdebitRowIndex = 6, ClosingCreditRowIndex = 7;
            int secondSheet = 0;
            int SnoIncrement = 1;
            while (lstClmwiseData.Count > secondSheet)
            {
                ws2.Cell(snoColIndex, snoRowIndex).Value = SnoIncrement;
                ws2.Cell(GLCodeColIndex, GLCodRowIndex).Value = lstClmwiseData[secondSheet];
                ws2.Cell(DescriptioColIndex, DescriptioRowIndex).Value = lstClmwiseData[secondSheet + 1];
                ws2.Cell(movementDebitColIndex, movementDebitRowIndex).Value = lstClmwiseData[secondSheet + 2];
                ws2.Cell(movementCreditColIndex, movementCreditRowIndex).Value = lstClmwiseData[secondSheet + 3];
                ws2.Cell(ClosingdebitcolIndex, ClosingdebitRowIndex).Value = lstClmwiseData[secondSheet + 4];
                ws2.Cell(ClosingCreditColIndex, ClosingCreditRowIndex).Value = lstClmwiseData[secondSheet + 5];
                snoColIndex++;
                GLCodeColIndex++;
                DescriptioColIndex++;
                movementDebitColIndex++;
                movementCreditColIndex++;
                ClosingdebitcolIndex++;
                ClosingCreditColIndex++;
                SnoIncrement++;
                secondSheet = secondSheet + 6;
    
            }
            string path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\Downloads\ReportUtitlity";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string FileName = workbook.Author + "_" + "Report_"+CellId+ "CellId" +"_" + $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss-fff}";
            workbook.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\Downloads\ReportUtitlity\" + FileName + ".xlsx");
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-13
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      相关资源
      最近更新 更多