C#Excel数据我可以覆盖现有文件吗?

时间:2022-08-28 14:45:48

Can I open an Excel file, display it in the datagridview, and overwrite the data in the DataGridView when I save it back to an open Excel file?

我可以打开Excel文件,在datagridview中显示它,并在将其保存回打开的Excel文件时覆盖DataGridView中的数据吗?

I only found a way to create and save new files and new sheets.

我只找到了创建和保存新文件和新工作表的方法。

But the way I want is not to create new files and new sheets.

但我想要的方式不是创建新文件和新工作表。

How can I overwrite existing Excel?

如何覆盖现有的Excel?

English is not my mother tongue, it is not good.

英语不是我的母语,它不好。

I have already tried with the below code.

我已经尝试过以下代码。

    {
        SaveFileDialog sfd2 = new SaveFileDialog();
        sfd2.Title = "Save as Excel File";
        sfd2.Filter = "Excel Files(2003)|*.xls|Excel Files(2007)|*.xlsx";
        sfd2.FileName = "";

        if (sfd2.ShowDialog() == DialogResult.OK)
        {
            try
            {
                // Excel프로그램을 실행
                excelApp = new Excel.Application();

                // 실행된 Excel프로그램에 통합문서를 추가
                wb = excelApp.Workbooks.Add();
                //텍스트 형식 지정범위
                Excel._Worksheet workSheet = wb.Worksheets.get_Item(1) as Excel._Worksheet;
                Excel.Range oRange;
                oRange = workSheet.get_Range("A1:A300", "S1:S300");
                oRange.Cells.NumberFormat = "@";

                oRange.EntireRow.AutoFit();
                oRange.EntireColumn.AutoFit();
                oRange.WrapText = false;


                //데이터 동시저장
                Map_DataGridView_To_ExcelSheet(dataGridView1, "Sheet1");
                excelApp.Worksheets.Add();                  
                Map_DataGridView_To_ExcelSheet(dataGridView2, "Sheet2");
                excelApp.Worksheets.Add();
                Map_DataGridView_To_ExcelSheet(dataGridView3, "Sheet3");

                //view4에 데이터가 있을때만 4번째 시트를 생성
                if (dataGridView4.DataSource != null)
                {
                    excelApp.Worksheets.Add();
                    Map_DataGridView_To_ExcelSheet(dataGridView4, "Sheet4");
                }

                //excelApp.Worksheets.Add();
                //Map_DataGridView_To_ExcelSheet(dataGridView5, "Sheet5");
                ws.Columns.AutoFit();
                // 여기서 저장경로를 변경하면 됩니다.
               wb.SaveAs(sfd2.FileName, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
           Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                wb.Close(true);
                excelApp.Quit();     
                MessageBox.Show("저장이 완료되었습니다.");
            }
            //메모리해제
            finally
            {
                releaseObject(ws);
                releaseObject(wb);
                releaseObject(excelApp);
            }
        }
    } 
    private void Map_DataGridView_To_ExcelSheet(DataGridView dataGridView, string sheetName)
    {
        // 지정된 문자열에 해당하는 Sheet를 가져옵니다.
        ws = wb.Worksheets.get_Item(sheetName) as Excel.Worksheet;

    if(dataGridView.DataSource != null)
    {
        for (int i = 0; i < dataGridView.ColumnCount; i++)
        {
            label5.Text = i.ToString();
            for (int j = 0; j < dataGridView.RowCount; j++)
            {
                label6.Text = j.ToString();
                // 워크시트 개체 ws의 Cells(Range 개체)와 DataGridView의 인덱스가 반대인것에 유의
                // 또한, Cells는 인덱스가 1부터 시작
                // ws.Cells[Row, Column]   // dataGridView[Column, Row]
                if (dataGridView[i, j].Value.ToString().Trim() != "")
                {
                    ws.Cells[j + 1, i + 1] = dataGridView[i, j].Value.ToString();
                }
            }
          }

1 个解决方案

#1


0  

Yes you can, but most people on SO aren't a code writing service so we don't really respond to requests like this. Try looking at tutorials for EPPlus, a well used and liked library for reading and writing excel files. You can also search SO for epplus and see what questions people have asked about it, maybe get together enough snippets. If you reach a point where you've done some work, and for example you can read your excel into a dataset but have no idea how to show that dataset's tables in a datagridview, feel free to post up a question (or search as it has certainly been asked before) like "how can I show a datatable in a datagridview" - that's the kind of question SO is designed to answer

是的,你可以,但SO上的大多数人都不是代码编写服务,所以我们并没有真正回应这样的请求。尝试查看EPPlus的教程,EPPlus是一个很好用和喜欢的库,用于读写excel文件。您还可以搜索SO以查找epplus,并查看人们提出的有关它的问题,也许可以聚集足够的片段。如果你达到了你已完成某项工作的地步,例如你可以将你的Excel读入数据集但不知道如何在数据网格视图中显示该数据集的表,随意发布一个问题(或搜索它之前一直被问到过“如何在数据网格视图中显示数据表” - 这就是SO旨在回答的问题

As a guide for the future, any questions that would have a long answer that is more like something you'd read in a blog, rather than an answer than can be written in 5 lines, should not really be asked on *

作为未来的指南,任何问题都会有很长的答案,更像是你在博客中读到的内容,而不是一个可以写成5行的答案,不应该在*上真正提出

#1


0  

Yes you can, but most people on SO aren't a code writing service so we don't really respond to requests like this. Try looking at tutorials for EPPlus, a well used and liked library for reading and writing excel files. You can also search SO for epplus and see what questions people have asked about it, maybe get together enough snippets. If you reach a point where you've done some work, and for example you can read your excel into a dataset but have no idea how to show that dataset's tables in a datagridview, feel free to post up a question (or search as it has certainly been asked before) like "how can I show a datatable in a datagridview" - that's the kind of question SO is designed to answer

是的,你可以,但SO上的大多数人都不是代码编写服务,所以我们并没有真正回应这样的请求。尝试查看EPPlus的教程,EPPlus是一个很好用和喜欢的库,用于读写excel文件。您还可以搜索SO以查找epplus,并查看人们提出的有关它的问题,也许可以聚集足够的片段。如果你达到了你已完成某项工作的地步,例如你可以将你的Excel读入数据集但不知道如何在数据网格视图中显示该数据集的表,随意发布一个问题(或搜索它之前一直被问到过“如何在数据网格视图中显示数据表” - 这就是SO旨在回答的问题

As a guide for the future, any questions that would have a long answer that is more like something you'd read in a blog, rather than an answer than can be written in 5 lines, should not really be asked on *

作为未来的指南,任何问题都会有很长的答案,更像是你在博客中读到的内容,而不是一个可以写成5行的答案,不应该在*上真正提出