简体   繁体   English

使用iterop.excel在C#中更新Excel工作表

[英]updating excel sheet in c# using iterop.excel

I am trying updating a excel sheet in c# and i am using interop.excel. 我正在尝试在C#中更新Excel工作表,并且正在使用interop.excel。 When i update a excel sheet this is update a single data. 当我更新Excel工作表时,这是更新单个数据。 I want all data update in a single excel sheet. 我希望所有数据都在一个Excel工作表中更新。 I am using this code 我正在使用此代码

`private void button1_Click(object sender, EventArgs e)
    {
        if (cnt1 >= 1)
        {
            connectionSilca();
            for (int counter = 0; counter < cnt1; counter++)
            {
                fcl.cmd = new OracleCommand("select book_id,book_title,category_id,author,book_pub,book_copies,publisher_name,isbn,copyright_year,date_added,status from book where book_id='" + listBox1.Items[counter].ToString() + "'", fcl.con);

                DataTable dt = new DataTable();
                DataSet DS = new DataSet();
                OracleDataAdapter AD = new OracleDataAdapter(cmd);
                OracleDataAdapter da = new OracleDataAdapter(cmd);
                da.Fill(dt);
                da.Fill(DS);
                //DataTable temptable = DS.Tables[0];
                //ExportToExcel(temptable);
                ExportToExcel(DS.Tables[0]);
            }
        }
        else
        {
            MessageBox.Show("Please Select Atleast One Item");
        }
        con.Close();
        MessageBox.Show("EXCEL DOWNLOAD SUCCESSFULLY");
        datarefresh();
    }

    public void ExportToExcel(DataTable dtCollection)
    {
        var ds = dtCollection;
        Microsoft.Office.Interop.Excel.Worksheet objWorkSheet1 = null;
        Microsoft.Office.Interop.Excel.Application objExcel = new Microsoft.Office.Interop.Excel.Application { Visible = false };
        Microsoft.Office.Interop.Excel.Workbooks objWorkbooks = objExcel.Workbooks;
        Microsoft.Office.Interop.Excel.Workbook objWorkbook = objWorkbooks.Add(Missing.Value);
        Microsoft.Office.Interop.Excel.Sheets objSheets = objWorkbook.Worksheets;
        Microsoft.Office.Interop.Excel.Range objCells;
        Microsoft.Office.Interop.Excel.Range myCell;

        //open the excel file form the location 
        //here is existing excel code
        string path = @"C:\\EXCEL\\DATA\\myData.xls";
        objExcel = new Microsoft.Office.Interop.Excel.Application();
        objExcel.DisplayAlerts = false;
        objWorkbook = objExcel.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
        objSheets = objWorkbook.Worksheets;
        //Get the allready exists sheet
        objWorkSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)objSheets.get_Item("Input");
        Microsoft.Office.Interop.Excel.Range range = objWorkSheet1.UsedRange;

        objWorkSheet1.Cells[5, 3]= 100000089;
        objWorkSheet1.Cells[5, 4] = 001;
        objWorkSheet1.Cells[5, 7] = System.DateTime.Now.ToString("ddMMyyyy");
        objWorkSheet1.Cells[5, 10] = "ASHSBCTS2017";

        var iCurrentRow = 12;
        var dt = ds;
        int columnsCount = dt.Columns.Count;
        objWorkSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)(objSheets[1]);
        objCells = objWorkSheet1.Cells;

        /*for (var h = 0; h < dt.Columns.Count; h++)
        {
            myCell = (Microsoft.Office.Interop.Excel.Range)objCells[iCurrentRow, h + 1];
            myCell.Value2 = dt.Columns[h].ColumnName;
        }
        iCurrentRow++;*/
        for (var r = 0; r < dt.Rows.Count; r++)
        {
            for (var c = 0; c < dt.Columns.Count; c++)
            {
                    if (dt.Columns[c].DataType.Name == "String" || dt.Columns[c].DataType.Name == "DateTime")
                    {
                        myCell = (Microsoft.Office.Interop.Excel.Range)objCells[r + iCurrentRow, c + 1];
                        myCell.Value2 = "'" + dt.Rows[r][c].ToString().Trim();
                    }
                    else
                    {
                        myCell = (Microsoft.Office.Interop.Excel.Range)objCells[r + iCurrentRow, c + 1];
                        myCell.Value2 = dt.Rows[r][c];
                    }
                }
            }
        //objWorkSheet1.Cells.EntireRow.AutoFit();
        //objWorkSheet1.Cells.EntireColumn.AutoFit();
        objWorkbook.SaveAs("C:\\EXCEL\\DATA\\myData.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel12, System.Reflection.Missing.Value, 
            System.Reflection.Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, false, false,
            System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
        objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);
        objExcel.Quit();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
    }`

How to solve this, please give me some solution for this Thanks in advance 如何解决这个问题,请为此给我一些解决方案

you may want to change the line 你可能想换行

objWorkSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)objSheets.get_Item("Input");

with

objWorkSheet1 =  = objWorkbook.Worksheets["Input"] as Worksheet;

Also as I mentioned in the comments, you should separate the read and the write. 另外,正如我在评论中提到的那样,您应该将读取和写入分开。 there is no need for the code below 不需要下面的代码

for (int counter = 0; counter < cnt1; counter++)
{
    .....
    ExportToExcel(DS.Tables[0]);
}

the 'ExportToExcel(DS.Tables[0]);' “ ExportToExcel(DS.Tables [0]);” should come out of that loop. 应该走出那个循环。

EDIT 编辑

using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Office.Interop.Excel;
using DataTable = System.Data.DataTable;

namespace ExcelExample
{
    internal class Test
    {
        private int _cnt1 = 0;
        private readonly List<DataTable> _dataTables = new List<DataTable>();

        private void button1_Click(object sender, EventArgs e)
        {
            ReadDataFromDatabase();
            ExportToExcel();
            DataRefresh();
        }

        private void ReadDataFromDatabase()
        {
            try
            {
                if (_cnt1 >= 1)
                {
                    _dataTables.Clear();
                    connectionSilca();
                    for (int counter = 0; counter < _cnt1; counter++)
                    {
                        fcl.cmd = new OracleCommand(
                            "select book_id,book_title,category_id,author,book_pub,book_copies,publisher_name,isbn,copyright_year,date_added,status from book where book_id='" +
                            listBox1.Items[counter].ToString() + "'", fcl.con);

                        var dataSet = new DataSet();

                        OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(cmd);
                        oracleDataAdapter.Fill(dataSet);
                        _dataTables.Add(dataSet.Tables[0]);
                    }
                }
                else
                {
                    MessageBox.Show("Please Select Atleast One Item");
                }
            }
            catch (Exception)
            {
                // catch any connection exceptions.
            }
            finally
            {
                con.Close();
            }
        }

        private void ExportToExcel()
        {
            //open the excel file form the location 
            //here is existing excel code
            const string path = @"C:\\EXCEL\\DATA\\myData.xls";
            var excelApplication = new Application(){Visible = false, DisplayAlerts = false};
            var workbook = excelApplication.Workbooks.Open(path, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            var workSheet = workbook.Worksheets["Input"] as Worksheet;

            if (workSheet != null)
            {
                workSheet.Cells[5, 3] = 100000089;
                workSheet.Cells[5, 4] = 001;
                workSheet.Cells[5, 7] = System.DateTime.Now.ToString("ddMMyyyy");
                workSheet.Cells[5, 10] = "ASHSBCTS2017";

                var cells = workSheet.Cells;
                var rowIndex = 12;

                foreach (var table in _dataTables)
                {
                    for (var r = 0; r < table.Rows.Count; r++)
                    {
                        for (var c = 0; c < table.Columns.Count; c++)
                        {
                            var currentCell = (Range)cells[rowIndex, c + 1];

                            if (table.Columns[c].DataType.Name == "String" || table.Columns[c].DataType.Name == "DateTime")
                            {
                                currentCell.Value2 = "'" + table.Rows[r][c].ToString().Trim();
                            }
                            else
                            {
                                currentCell.Value2 = table.Rows[r][c];
                            }
                        }
                        rowIndex++;
                    }
                }
            }

            workbook.SaveAs("C:\\EXCEL\\DATA\\myData.xls", XlFileFormat.xlExcel12, System.Reflection.Missing.Value,
                System.Reflection.Missing.Value, false, false, XlSaveAsAccessMode.xlShared, false, false,
                System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
            workbook.Close();
            excelApplication.Quit();

            MessageBox.Show("EXCEL DOWNLOAD SUCCESSFULLY");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM