Tuesday, 31 October 2023 03:44

C# Excel에서 주석 편집 또는 삭제

NuGet을 통해 설치됨

PM> Install-Package Spire.XLS

관련된 링크들

Excel 주석은 더 자세한 설명을 제공하거나 다른 사용자에게 팁을 제공하기 위해 지정된 셀에 추가할 수 있는 추가 메모 또는 설명입니다. 메모가 추가되면 Excel은 워크시트에서 메모의 형식을지정하고, 편집하고, 삭제하고, 표시/숨길 수 있는 유연성을 사용자에게 제공합니다. 이 기사에서는 프로그래밍 방식으로 방법을 배웁니다 Spire.XLS for .NET사용하여 Excel에서 기존 주석을 편집하거나 삭제합니다.

Spire.XLS for .NET 설치

먼저 Spire.XLS for.NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크 에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.

PM> Install-Package Spire.XLS

Excel에서 주석 편집

Excel 통합 문서에 메모를 추가한 후 추가된 메모를 변경해야 하는 경우가 있습니다. 아래 표에는 기존 주석을 가져온 다음 새 텍스트와 주석 서식을 설정하는 데 사용되는 일부 핵심 클래스와 속성이 나열되어 있습니다.

이름 설명
CellRange.Comment 속성 범위의 왼쪽 위 모서리에 있는 셀과 연결된 설명을 나타내는 Comment 개체를 반환합니다.
ExcelCommentObject 클래스 댓글을 나타냅니다.
ExcelCommentObject.Text 속성 주석 텍스트를 가져오거나 설정합니다.
ExcelCommentObject.Height 속성 댓글의 높이를 가져오거나 설정합니다.
ExcelCommentObject.Width 속성 주석의 너비를 가져오거나 설정합니다.
ExcelCommentObject.AutoSize 속성 지정된 개체의 크기가 해당 경계 내에 텍스트에 맞게 자동으로 변경되는지 여부를 나타냅니다.

Excel에서 주석을 편집하는 단계는 다음과 같습니다.

  • 통합 문서 인스턴스를 만듭니다.
  • Workbook.LoadFromFile() 메서드를 사용하여 Excel 파일을 로드합니다.
  • Workbook.Worksheets[] 속성을 사용하여 Excel 파일의 첫 번째 워크시트를 가져옵니다.
  • Worksheet.Range.Comment 속성을 사용하여 특정 셀 범위에서 주석을 가져옵니다.
  • ExcelCommentObject 클래스의 속성을 사용하여 기존 주석의 새 텍스트와 높이/너비 또는 자동 크기를 설정합니다.
  • Workbook.SaveToFile() 메서드를 사용하여 문서를 다른 파일에 저장합니다.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace EditExcelComment
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Create a Workbook instance
                Workbook workbook = new Workbook();
    
                // Load an Excel file
                workbook.LoadFromFile("Comments.xlsx");
    
                // Get the first worksheet
                Worksheet sheet = workbook.Worksheets[0];
    
                //Get comments in specific cells and set new comments
                sheet.Range["A8"].Comment.Text = "Frank has left the company.";
                sheet.Range["F6"].Comment.Text = "Best sales.";
    
                // Set the height and width of the new comments
                sheet.Range["A8"].Comment.Height = 50;
                sheet.Range["A8"].Comment.Width = 100;
                sheet.Range["F6"].Comment.AutoSize = true;
    
    
                // Save to file.
                workbook.SaveToFile("ModifyComment.xlsx", ExcelVersion.Version2013);
            }
        }
    }

C#/VB.NET: Edit or Delete Comments in Excel

Excel에서 메모 삭제

Spire.XLS for .NET에서 제공하는 ExcelCommentObject.Remove() 메서드를 사용하면 지정된 주석을 쉽게 제거할 수 있습니다. 자세한 단계는 다음과 같습니다.

  • 통합 문서 인스턴스를 만듭니다.
  • Workbook.LoadFromFile() 메서드를 사용하여 Excel 파일을 로드합니다.
  • Workbook.Worksheets[] 속성을 사용하여 Excel 파일의 첫 번째 워크시트를 가져옵니다.
  • Worksheet.Range.Comment 속성을 사용하여 특정 셀 범위의 메모를 가져온 다음 ExcelCommentObject.Remove() 메서드를 사용하여 메모를 삭제합니다.
  • Workbook.SaveToFile() 메서드를 사용하여 문서를 다른 파일에 저장합니다.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace EditExcelComment
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Create a Workbook instance
                Workbook workbook = new Workbook();
    
                // Load an Excel file
                workbook.LoadFromFile("Comments.xlsx");
    
                // Get the first worksheet
                Worksheet sheet = workbook.Worksheets[0];
    
                //Get the comment in a specific cell and remove it
                sheet.Range["F6"].Comment.Remove();
    
                // Save to file.
                workbook.SaveToFile("DeleteComment.xlsx", ExcelVersion.Version2013);
            }
        }
    }

C#/VB.NET: Edit or Delete Comments in Excel

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

또한보십시오

Tuesday, 31 October 2023 03:44

C# Modifica o elimina commenti in Excel

Installato tramite NuGet

PM> Install-Package Spire.XLS

Link correlati

I commenti di Excel sono note o commenti aggiuntivi che possono essere aggiunti a celle specifiche per fornire spiegazioni più approfondite o offrire suggerimenti ad altri utenti. Una volta aggiunto un commento, Excel offre agli utenti la flessibilità di formattare, modificare, eliminare e mostrare/nascondere il commento nel foglio di lavoro. In questo articolo imparerai come farlo a livello di codice modificare o eliminare i commenti esistenti in Excel utilizzando Spire.XLS for .NET.

Installa Spire.XLS for .NET

Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.XLS for .NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

PM> Install-Package Spire.XLS

Modifica commenti in Excel

Dopo aver aggiunto commenti alla cartella di lavoro di Excel, a volte potrebbe essere necessario apportare modifiche ai commenti aggiunti. La tabella seguente elenca alcune delle classi e proprietà principali utilizzate per ottenere i commenti esistenti e quindi impostare il nuovo testo e la formattazione per i commenti.

Nome Descrizione
Proprietà CellRange.Comment Restituisce un oggetto Comment che rappresenta il commento associato alla cella nell'angolo superiore sinistro dell'intervallo.
Classe ExcelCommentObject Rappresenta un commento.
Proprietà ExcelCommentObject.Text Ottiene o imposta il testo del commento.
Proprietà ExcelCommentObject.Height Ottiene o imposta l'altezza di un commento.
Proprietà ExcelCommentObject.Width Ottiene o imposta la larghezza di un commento.
Proprietà ExcelCommentObject.AutoSize Indica se la dimensione dell'oggetto specificato viene modificata automaticamente per adattare il testo entro i suoi limiti.

Di seguito sono riportati i passaggi per modificare i commenti in Excel:

  • Crea un'istanza della cartella di lavoro.
  • Carica un file Excel utilizzando il metodo Workbook.LoadFromFile().
  • Ottieni il primo foglio di lavoro del file Excel utilizzando la proprietà Workbook.Worksheets[].
  • Ottieni un commento in un intervallo di celle specifico utilizzando la proprietà Worksheet.Range.Comment.
  • Imposta il nuovo testo e l'altezza/larghezza o la dimensione automatica per il commento esistente utilizzando le proprietà della classe ExcelCommentObject.
  • Salva il documento in un altro file utilizzando il metodo Workbook.SaveToFile().
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace EditExcelComment
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Create a Workbook instance
                Workbook workbook = new Workbook();
    
                // Load an Excel file
                workbook.LoadFromFile("Comments.xlsx");
    
                // Get the first worksheet
                Worksheet sheet = workbook.Worksheets[0];
    
                //Get comments in specific cells and set new comments
                sheet.Range["A8"].Comment.Text = "Frank has left the company.";
                sheet.Range["F6"].Comment.Text = "Best sales.";
    
                // Set the height and width of the new comments
                sheet.Range["A8"].Comment.Height = 50;
                sheet.Range["A8"].Comment.Width = 100;
                sheet.Range["F6"].Comment.AutoSize = true;
    
    
                // Save to file.
                workbook.SaveToFile("ModifyComment.xlsx", ExcelVersion.Version2013);
            }
        }
    }

C#/VB.NET: Edit or Delete Comments in Excel

Elimina commenti in Excel

Il metodo ExcelCommentObject.Remove() offerto da Spire.XLS for .NET consente di rimuovere facilmente un commento specificato. I passaggi dettagliati sono i seguenti:

  • Crea un'istanza della cartella di lavoro.
  • Carica un file Excel utilizzando il metodo Workbook.LoadFromFile().
  • Ottieni il primo foglio di lavoro del file Excel utilizzando la proprietà Workbook.Worksheets[].
  • Ottieni un commento in un intervallo di celle specifico utilizzando la proprietà Worksheet.Range.Comment e quindi elimina il commento utilizzando il metodo ExcelCommentObject.Remove().
  • Salva il documento in un altro file utilizzando il metodo Workbook.SaveToFile().
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace EditExcelComment
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Create a Workbook instance
                Workbook workbook = new Workbook();
    
                // Load an Excel file
                workbook.LoadFromFile("Comments.xlsx");
    
                // Get the first worksheet
                Worksheet sheet = workbook.Worksheets[0];
    
                //Get the comment in a specific cell and remove it
                sheet.Range["F6"].Comment.Remove();
    
                // Save to file.
                workbook.SaveToFile("DeleteComment.xlsx", ExcelVersion.Version2013);
            }
        }
    }

C#/VB.NET: Edit or Delete Comments in Excel

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

Installé via NuGet

PM> Install-Package Spire.XLS

Les commentaires Excel sont des notes ou des commentaires supplémentaires qui peuvent être ajoutés à des cellules spécifiées pour fournir des explications plus approfondies ou pour offrir des conseils aux autres utilisateurs. Une fois qu'un commentaire a été ajouté, Excel offre aux utilisateurs la possibilité de formater, modifier, supprimer et afficher/masquer le commentaire dans la feuille de calcul. Dans cet article, vous apprendrez à programmer modifiez ou supprimez des commentaires existants dans Excel à l’aide de Spire.XLS for .NET.

Installez Spire.XLS for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.XLS for.NET comme références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.

PM> Install-Package Spire.XLS

Modifier les commentaires dans Excel

Après avoir ajouté des commentaires à votre classeur Excel, vous devrez parfois apporter des modifications aux commentaires ajoutés. Le tableau ci-dessous répertorie certaines des classes et propriétés principales utilisées pour obtenir les commentaires existants, puis définir un nouveau texte ainsi que le formatage des commentaires.

Nom Description
Propriété CellRange.Comment Renvoie un objet Comment qui représente le commentaire associé à la cellule dans le coin supérieur gauche de la plage.
Classe ExcelCommentObject Représente un commentaire.
Propriété ExcelCommentObject.Text Obtient ou définit le texte du commentaire.
Propriété ExcelCommentObject.Height Obtient ou définit la hauteur d'un commentaire.
Propriété ExcelCommentObject.Width Obtient ou définit la largeur d'un commentaire.
Propriété ExcelCommentObject.AutoSize Indique si la taille de l'objet spécifié est modifiée automatiquement pour adapter le texte à ses limites.

Voici les étapes pour modifier les commentaires dans Excel :

  • Créez une instance de classeur.
  • Chargez un fichier Excel à l'aide de la méthode Workbook.LoadFromFile().
  • Obtenez la première feuille de calcul du fichier Excel à l’aide de la propriété Workbook.Worksheets[].
  • Obtenez un commentaire dans une plage de cellules spécifique à l’aide de la propriété Worksheet.Range.Comment.
  • Définissez le nouveau texte et la hauteur/largeur ou la taille automatique pour le commentaire existant à l'aide des propriétés de la classe ExcelCommentObject.
  • Enregistrez le document dans un autre fichier à l'aide de la méthode Workbook.SaveToFile().
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace EditExcelComment
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Create a Workbook instance
                Workbook workbook = new Workbook();
    
                // Load an Excel file
                workbook.LoadFromFile("Comments.xlsx");
    
                // Get the first worksheet
                Worksheet sheet = workbook.Worksheets[0];
    
                //Get comments in specific cells and set new comments
                sheet.Range["A8"].Comment.Text = "Frank has left the company.";
                sheet.Range["F6"].Comment.Text = "Best sales.";
    
                // Set the height and width of the new comments
                sheet.Range["A8"].Comment.Height = 50;
                sheet.Range["A8"].Comment.Width = 100;
                sheet.Range["F6"].Comment.AutoSize = true;
    
    
                // Save to file.
                workbook.SaveToFile("ModifyComment.xlsx", ExcelVersion.Version2013);
            }
        }
    }

C#/VB.NET: Edit or Delete Comments in Excel

Supprimer des commentaires dans Excel

La méthode ExcelCommentObject.Remove() proposée par Spire.XLS for .NET vous permet de supprimer facilement un commentaire spécifié. Les étapes détaillées sont les suivantes :

  • Créez une instance de classeur.
  • Chargez un fichier Excel à l'aide de la méthode Workbook.LoadFromFile().
  • Obtenez la première feuille de calcul du fichier Excel à l’aide de la propriété Workbook.Worksheets[].
  • Obtenez un commentaire dans une plage de cellules spécifique à l’aide de la propriété Worksheet.Range.Comment, puis supprimez le commentaire à l’aide de la méthode ExcelCommentObject.Remove().
  • Enregistrez le document dans un autre fichier à l'aide de la méthode Workbook.SaveToFile().
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace EditExcelComment
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Create a Workbook instance
                Workbook workbook = new Workbook();
    
                // Load an Excel file
                workbook.LoadFromFile("Comments.xlsx");
    
                // Get the first worksheet
                Worksheet sheet = workbook.Worksheets[0];
    
                //Get the comment in a specific cell and remove it
                sheet.Range["F6"].Comment.Remove();
    
                // Save to file.
                workbook.SaveToFile("DeleteComment.xlsx", ExcelVersion.Version2013);
            }
        }
    }

C#/VB.NET: Edit or Delete Comments in Excel

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Tuesday, 31 October 2023 03:39

C# Copy Worksheets in Excel

Installed via NuGet

PM> Install-Package Spire.XLS

Related Links

Excel copy function enables you to not only copy worksheets within Excel workbook but also copy worksheets between different Excel workbooks. This article will introduce solutions to copy worksheets within one Excel workbook and among different workbooks via Spire.XLS for .NET in C#, VB.NET. Besides, all the cell formats in the original Excel worksheets will be completely remained.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.

  • Package Manager
PM> Install-Package Spire.XLS

Copy Excel Worksheets within Excel Workbook

The following are the steps to duplicate worksheets within an Excel workbook.

  • Initialize an instance of Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Add a new blank sheet to the workbook using WorksheetCollection.Add() method.
  • Copy the original worksheet to the new sheet using Worksheet.CopyFrom() method.
  • Use Workbook.SaveToFile() method to save the changes to another file.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
    
                //Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy");
    
               //copy worksheet to the new added worksheets
               workbook.Worksheets[1].CopyFrom(workbook.Worksheets[0]);
    
                //Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013);
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                'Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy")
                'copy worksheet to the new added worksheets
                workbook.Worksheets(1).CopyFrom(workbook.Worksheets(0))
                'Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013)
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Copy Excel Worksheets between Excel Workbooks

The following are the steps to duplicate worksheets within an Excel workbook.

  • Initialize an instance of Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get the first worksheet.
  • Load another Excel sample document
  • Add a new blank sheet to the second workbook using WorksheetCollection.Add() method.
  • Copy the original worksheet to the new sheet using Worksheet.CopyFrom() method.
  • Use Workbook.SaveToFile() method to save the changes to another file.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel and get the first worksheet
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
                Worksheet sheet = workbook.Worksheets[0];
                //Load the second Excel workbook
                Workbook workbook2 = new Workbook();
                workbook2.LoadFromFile("New.xlsx");
                //Add a new worksheet and set its name
                Worksheet targetWorksheet = workbook2.Worksheets.Add("added");
                //Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet);
                //Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013);
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel and get the first worksheet
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                Dim sheet As Worksheet = workbook.Worksheets(0)
                'Load the second Excel workbook
                Dim workbook2 As Workbook = New Workbook
                workbook2.LoadFromFile("New.xlsx")
                'Add a new worksheet and set its name
                Dim targetWorksheet As Worksheet = workbook2.Worksheets.Add("added")
                'Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet)
                'Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013)
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

See Also

Tuesday, 31 October 2023 03:38

C# Copiar planilhas no Excel

A função de cópia do Excel permite não apenas copiar planilhas dentro da pasta de trabalho do Excel, mas também copiar planilhas entre diferentes pastas de trabalho do Excel. Este artigo apresentará soluções para copiar planilhas dentro de uma pasta de trabalho do Excel e entre diferentes pastas de trabalho via Spire.XLS for .NET em C#, VB.NET. Além disso, todos os formatos de células nas planilhas originais do Excel permanecerão completamente.

Instale o Spire.XLS for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.XLS for .NET como referências em seu projeto .NET. Os arquivos DLLs podem ser baixados deste link ou instalados via NuGet.

  • Package Manager
PM> Install-Package Spire.XLS

Copie planilhas do Excel na pasta de trabalho do Excel

A seguir estão as etapas para duplicar planilhas em uma pasta de trabalho do Excel.

  • Inicialize uma instância da classe Workbook.
  • Carregue um arquivo Excel usando o método Workbook.LoadFromFile().
  • Adicione uma nova planilha em branco à pasta de trabalho usando o método WorksheetCollection.Add().
  • Copie a planilha original para a nova planilha usando o método Worksheet.CopyFrom().
  • Use o método Workbook.SaveToFile() para salvar as alterações em outro arquivo.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
    
                //Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy");
    
               //copy worksheet to the new added worksheets
               workbook.Worksheets[1].CopyFrom(workbook.Worksheets[0]);
    
                //Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013);
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                'Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy")
                'copy worksheet to the new added worksheets
                workbook.Worksheets(1).CopyFrom(workbook.Worksheets(0))
                'Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013)
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Copiar planilhas do Excel entre pastas de trabalho do Excel

A seguir estão as etapas para duplicar planilhas em uma pasta de trabalho do Excel.

  • Inicialize uma instância da classe Workbook.
  • Carregue um arquivo Excel usando o método Workbook.LoadFromFile().
  • Obtenha a primeira planilha.
  • Carregue outro documento de amostra do Excel
  • Adicione uma nova planilha em branco à segunda pasta de trabalho usando o método WorksheetCollection.Add().
  • Copie a planilha original para a nova planilha usando o método Worksheet.CopyFrom().
  • Use o método Workbook.SaveToFile() para salvar as alterações em outro arquivo.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel and get the first worksheet
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
                Worksheet sheet = workbook.Worksheets[0];
                //Load the second Excel workbook
                Workbook workbook2 = new Workbook();
                workbook2.LoadFromFile("New.xlsx");
                //Add a new worksheet and set its name
                Worksheet targetWorksheet = workbook2.Worksheets.Add("added");
                //Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet);
                //Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013);
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel and get the first worksheet
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                Dim sheet As Worksheet = workbook.Worksheets(0)
                'Load the second Excel workbook
                Dim workbook2 As Workbook = New Workbook
                workbook2.LoadFromFile("New.xlsx")
                'Add a new worksheet and set its name
                Dim targetWorksheet As Worksheet = workbook2.Worksheets.Add("added")
                'Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet)
                'Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013)
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Solicite uma licença temporária

Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também

Функция копирования Excel позволяет не только копировать листы внутри книги Excel, но также копировать листы между разными книгами Excel. В этой статье будут представлены решения для копирования листов в одной книге Excel и между разными книгами с помощью Spire.XLS for .NET в C#, VB.NET. Кроме того, все форматы ячеек в исходных листах Excel будут полностью сохранены.

Установите Spire.XLS for .NET

Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.XLS for .NET , в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

  • Package Manager
PM> Install-Package Spire.XLS

Копирование листов Excel в книгу Excel

Ниже приведены шаги по дублированию листов в книге Excel.

  • Инициализируйте экземпляр класса Workbook.
  • Загрузите файл Excel с помощью метода Workbook.LoadFromFile().
  • Добавьте новый пустой лист в книгу с помощью метода WorksheetCollection.Add().
  • Скопируйте исходный лист на новый лист, используя метод Worksheet.CopyFrom().
  • Используйте метод Workbook.SaveToFile(), чтобы сохранить изменения в другой файл.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
    
                //Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy");
    
               //copy worksheet to the new added worksheets
               workbook.Worksheets[1].CopyFrom(workbook.Worksheets[0]);
    
                //Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013);
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                'Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy")
                'copy worksheet to the new added worksheets
                workbook.Worksheets(1).CopyFrom(workbook.Worksheets(0))
                'Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013)
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Копирование листов Excel между книгами Excel

Ниже приведены шаги по дублированию листов в книге Excel.

  • Инициализируйте экземпляр класса Workbook.
  • Загрузите файл Excel с помощью метода Workbook.LoadFromFile().
  • Получите первый рабочий лист.
  • Загрузите еще один образец документа Excel
  • Добавьте новый пустой лист во вторую книгу с помощью метода WorksheetCollection.Add().
  • Скопируйте исходный лист на новый лист, используя метод Worksheet.CopyFrom().
  • Используйте метод Workbook.SaveToFile(), чтобы сохранить изменения в другой файл.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel and get the first worksheet
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
                Worksheet sheet = workbook.Worksheets[0];
                //Load the second Excel workbook
                Workbook workbook2 = new Workbook();
                workbook2.LoadFromFile("New.xlsx");
                //Add a new worksheet and set its name
                Worksheet targetWorksheet = workbook2.Worksheets.Add("added");
                //Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet);
                //Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013);
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel and get the first worksheet
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                Dim sheet As Worksheet = workbook.Worksheets(0)
                'Load the second Excel workbook
                Dim workbook2 As Workbook = New Workbook
                workbook2.LoadFromFile("New.xlsx")
                'Add a new worksheet and set its name
                Dim targetWorksheet As Worksheet = workbook2.Worksheets.Add("added")
                'Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet)
                'Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013)
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Подать заявку на временную лицензию

Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.

Смотрите также

Tuesday, 31 October 2023 03:36

C# Arbeitsblätter in Excel kopieren

Mit der Excel-Kopierfunktion können Sie nicht nur Arbeitsblätter innerhalb einer Excel-Arbeitsmappe kopieren, sondern auch Arbeitsblätter zwischen verschiedenen Excel-Arbeitsmappen kopieren. In diesem Artikel werden Lösungen zum Kopieren von Arbeitsblättern innerhalb einer Excel-Arbeitsmappe und zwischen verschiedenen Arbeitsmappen über Spire.XLS for .NET in C#, VB.NET vorgestellt. Außerdem bleiben alle Zellformate in den ursprünglichen Excel-Arbeitsblättern vollständig erhalten.

Installieren Sie Spire.XLS for .NET

Zunächst müssen Sie die im Spire.XLS for .NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLLs-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.

  • Package Manager
PM> Install-Package Spire.XLS

Kopieren Sie Excel-Arbeitsblätter in eine Excel-Arbeitsmappe

Im Folgenden finden Sie die Schritte zum Duplizieren von Arbeitsblättern in einer Excel-Arbeitsmappe.

  • Initialisieren Sie eine Instanz der Workbook-Klasse.
  • Laden Sie eine Excel-Datei mit der Methode Workbook.LoadFromFile().
  • Fügen Sie der Arbeitsmappe mit der Methode WorksheetCollection.Add() ein neues leeres Blatt hinzu.
  • Kopieren Sie das ursprüngliche Arbeitsblatt mit der Methode Worksheet.CopyFrom() in das neue Blatt.
  • Verwenden Sie die Methode Workbook.SaveToFile(), um die Änderungen in einer anderen Datei zu speichern.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
    
                //Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy");
    
               //copy worksheet to the new added worksheets
               workbook.Worksheets[1].CopyFrom(workbook.Worksheets[0]);
    
                //Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013);
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                'Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy")
                'copy worksheet to the new added worksheets
                workbook.Worksheets(1).CopyFrom(workbook.Worksheets(0))
                'Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013)
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Kopieren Sie Excel-Arbeitsblätter zwischen Excel-Arbeitsmappen

Im Folgenden finden Sie die Schritte zum Duplizieren von Arbeitsblättern in einer Excel-Arbeitsmappe.

  • Initialisieren Sie eine Instanz der Workbook-Klasse.
  • Laden Sie eine Excel-Datei mit der Methode Workbook.LoadFromFile().
  • Holen Sie sich das erste Arbeitsblatt.
  • Laden Sie ein weiteres Excel-Beispieldokument
  • Fügen Sie der zweiten Arbeitsmappe mit der Methode WorksheetCollection.Add() ein neues leeres Blatt hinzu.
  • Kopieren Sie das ursprüngliche Arbeitsblatt mit der Methode Worksheet.CopyFrom() in das neue Blatt.
  • Verwenden Sie die Methode Workbook.SaveToFile(), um die Änderungen in einer anderen Datei zu speichern.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel and get the first worksheet
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
                Worksheet sheet = workbook.Worksheets[0];
                //Load the second Excel workbook
                Workbook workbook2 = new Workbook();
                workbook2.LoadFromFile("New.xlsx");
                //Add a new worksheet and set its name
                Worksheet targetWorksheet = workbook2.Worksheets.Add("added");
                //Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet);
                //Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013);
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel and get the first worksheet
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                Dim sheet As Worksheet = workbook.Worksheets(0)
                'Load the second Excel workbook
                Dim workbook2 As Workbook = New Workbook
                workbook2.LoadFromFile("New.xlsx")
                'Add a new worksheet and set its name
                Dim targetWorksheet As Worksheet = workbook2.Worksheets.Add("added")
                'Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet)
                'Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013)
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

Tuesday, 31 October 2023 03:35

C# Copiar hojas de trabajo en Excel

Instalado a través de NuGet

PM> Install-Package Spire.XLS

enlaces relacionados

La función de copia de Excel le permite no solo copiar hojas de trabajo dentro de un libro de Excel, sino también copiar hojas de trabajo entre diferentes libros de Excel. Este artículo presentará soluciones para copiar hojas de trabajo dentro de un libro de Excel y entre diferentes libros a través de Spire.XLS for .NET en C#, VB.NET. Además, todos los formatos de celda de las hojas de cálculo originales de Excel se mantendrán por completo.

Instalar Spire.XLS for .NET

Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.XLS for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalar a través de NuGet.

  • Package Manager
PM> Install-Package Spire.XLS

Copie hojas de trabajo de Excel dentro del libro de Excel

Los siguientes son los pasos para duplicar hojas de trabajo dentro de un libro de Excel.

  • Inicialice una instancia de la clase Workbook.
  • Cargue un archivo de Excel usando el método Workbook.LoadFromFile().
  • Agregue una nueva hoja en blanco al libro usando el método WorksheetCollection.Add().
  • Copie la hoja de trabajo original a la nueva hoja usando el método Worksheet.CopyFrom().
  • Utilice el método Workbook.SaveToFile() para guardar los cambios en otro archivo.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
    
                //Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy");
    
               //copy worksheet to the new added worksheets
               workbook.Worksheets[1].CopyFrom(workbook.Worksheets[0]);
    
                //Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013);
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                'Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy")
                'copy worksheet to the new added worksheets
                workbook.Worksheets(1).CopyFrom(workbook.Worksheets(0))
                'Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013)
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Copie hojas de trabajo de Excel entre libros de Excel

Los siguientes son los pasos para duplicar hojas de trabajo dentro de un libro de Excel.

  • Inicialice una instancia de la clase Workbook.
  • Cargue un archivo de Excel usando el método Workbook.LoadFromFile().
  • Obtenga la primera hoja de trabajo.
  • Cargue otro documento de muestra de Excel
  • Agregue una nueva hoja en blanco al segundo libro usando el método WorksheetCollection.Add().
  • Copie la hoja de trabajo original a la nueva hoja usando el método Worksheet.CopyFrom().
  • Utilice el método Workbook.SaveToFile() para guardar los cambios en otro archivo.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel and get the first worksheet
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
                Worksheet sheet = workbook.Worksheets[0];
                //Load the second Excel workbook
                Workbook workbook2 = new Workbook();
                workbook2.LoadFromFile("New.xlsx");
                //Add a new worksheet and set its name
                Worksheet targetWorksheet = workbook2.Worksheets.Add("added");
                //Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet);
                //Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013);
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel and get the first worksheet
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                Dim sheet As Worksheet = workbook.Worksheets(0)
                'Load the second Excel workbook
                Dim workbook2 As Workbook = New Workbook
                workbook2.LoadFromFile("New.xlsx")
                'Add a new worksheet and set its name
                Dim targetWorksheet As Worksheet = workbook2.Worksheets.Add("added")
                'Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet)
                'Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013)
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Solicite una licencia temporal

Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.

Ver también

Tuesday, 31 October 2023 03:34

C# Excel에서 워크시트 복사

Excel 복사 기능을 사용하면 Excel 통합 문서 내의 워크시트를 복사할 수 있을 뿐만 아니라 서로 다른 Excel 통합 문서 간에 워크시트를 복사할 수도 있습니다. 이 기사에서는 C#, VB.NET의 Spire.XLS for .NET을 통해 하나의 Excel 통합 문서 내에서 그리고 여러 통합 문서 간에 워크시트를 복사하는 솔루션을 소개합니다. 게다가 원본 Excel 워크시트의 모든 셀 형식은 완전히 유지됩니다.

Spire.XLS for .NET 설치

먼저 .NET 프로젝트의 참조로 Spire.XLS for .NET 패키지에 포함된 DLL 파일을 추가해야 합니다. DLL 파일은 이 링크에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.

  • Package Manager
PM> Install-Package Spire.XLS

Excel 통합 문서 내에서 Excel 워크시트 복사

다음은 Excel 통합 문서 내에서 워크시트를 복제하는 단계입니다.

  • Workbook 클래스의 인스턴스를 초기화합니다.
  • Workbook.LoadFromFile() 메서드를 사용하여 Excel 파일을 로드합니다.
  • WorksheetCollection.Add() 메서드를 사용하여 통합 문서에 새 빈 시트를 추가합니다.
  • Worksheet.CopyFrom() 메서드를 사용하여 원본 워크시트를 새 시트에 복사합니다.
  • Workbook.SaveToFile() 메서드를 사용하여 변경 사항을 다른 파일에 저장합니다.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
    
                //Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy");
    
               //copy worksheet to the new added worksheets
               workbook.Worksheets[1].CopyFrom(workbook.Worksheets[0]);
    
                //Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013);
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                'Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy")
                'copy worksheet to the new added worksheets
                workbook.Worksheets(1).CopyFrom(workbook.Worksheets(0))
                'Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013)
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Excel 통합 문서 간에 Excel 워크시트 복사

다음은 Excel 통합 문서 내에서 워크시트를 복제하는 단계입니다.

  • Workbook 클래스의 인스턴스를 초기화합니다.
  • Workbook.LoadFromFile() 메서드를 사용하여 Excel 파일을 로드합니다.
  • 첫 번째 워크시트를 가져옵니다.
  • 다른 Excel 샘플 문서 로드
  • WorksheetCollection.Add() 메서드를 사용하여 두 번째 통합 문서에 새 빈 시트를 추가합니다.
  • Worksheet.CopyFrom() 메서드를 사용하여 원본 워크시트를 새 시트에 복사합니다.
  • Workbook.SaveToFile() 메서드를 사용하여 변경 사항을 다른 파일에 저장합니다.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel and get the first worksheet
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
                Worksheet sheet = workbook.Worksheets[0];
                //Load the second Excel workbook
                Workbook workbook2 = new Workbook();
                workbook2.LoadFromFile("New.xlsx");
                //Add a new worksheet and set its name
                Worksheet targetWorksheet = workbook2.Worksheets.Add("added");
                //Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet);
                //Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013);
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel and get the first worksheet
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                Dim sheet As Worksheet = workbook.Worksheets(0)
                'Load the second Excel workbook
                Dim workbook2 As Workbook = New Workbook
                workbook2.LoadFromFile("New.xlsx")
                'Add a new worksheet and set its name
                Dim targetWorksheet As Worksheet = workbook2.Worksheets.Add("added")
                'Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet)
                'Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013)
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

또한보십시오

Tuesday, 31 October 2023 03:33

C# Copia fogli di lavoro in Excel

La funzione di copia di Excel consente non solo di copiare fogli di lavoro all'interno della cartella di lavoro di Excel, ma anche di copiare fogli di lavoro tra diverse cartelle di lavoro di Excel. Questo articolo introdurrà soluzioni per copiare fogli di lavoro all'interno di una cartella di lavoro Excel e tra cartelle di lavoro diverse tramite Spire.XLS for .NET in C#, VB.NET. Inoltre, tutti i formati delle celle nei fogli di lavoro Excel originali verranno mantenuti completamente.

Installa Spire.XLS for .NET

Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.XLS for .NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

  • Package Manager
PM> Install-Package Spire.XLS

Copia fogli di lavoro Excel all'interno della cartella di lavoro Excel

Di seguito sono riportati i passaggi per duplicare i fogli di lavoro all'interno di una cartella di lavoro di Excel.

  • Inizializza un'istanza della classe Workbook.
  • Carica un file Excel utilizzando il metodo Workbook.LoadFromFile().
  • Aggiungi un nuovo foglio vuoto alla cartella di lavoro utilizzando il metodo WorksheetCollection.Add().
  • Copia il foglio di lavoro originale sul nuovo foglio utilizzando il metodo Worksheet.CopyFrom().
  • Utilizzare il metodo Workbook.SaveToFile() per salvare le modifiche in un altro file.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
    
                //Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy");
    
               //copy worksheet to the new added worksheets
               workbook.Worksheets[1].CopyFrom(workbook.Worksheets[0]);
    
                //Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013);
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                'Add worksheet and set its name
                workbook.Worksheets.Add("Sheet1_Copy")
                'copy worksheet to the new added worksheets
                workbook.Worksheets(1).CopyFrom(workbook.Worksheets(0))
                'Save the Excel workbook.
                workbook.SaveToFile("Duplicatesheet.xlsx", ExcelVersion.Version2013)
                System.Diagnostics.Process.Start("Duplicatesheet.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Copia fogli di lavoro Excel tra cartelle di lavoro Excel

Di seguito sono riportati i passaggi per duplicare i fogli di lavoro all'interno di una cartella di lavoro di Excel.

  • Inizializza un'istanza della classe Workbook.
  • Carica un file Excel utilizzando il metodo Workbook.LoadFromFile().
  • Ottieni il primo foglio di lavoro.
  • Carica un altro documento di esempio Excel.
  • Aggiungi un nuovo foglio vuoto alla seconda cartella di lavoro utilizzando il metodo WorksheetCollection.Add().
  • Copia il foglio di lavoro originale sul nuovo foglio utilizzando il metodo Worksheet.CopyFrom().
  • Utilizzare il metodo Workbook.SaveToFile() per salvare le modifiche in un altro file.
  • C#
  • VB.NET
using Spire.Xls;
    
    namespace CopyExcelworksheet
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load the sample Excel and get the first worksheet
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Sample.xlsx");
                Worksheet sheet = workbook.Worksheets[0];
                //Load the second Excel workbook
                Workbook workbook2 = new Workbook();
                workbook2.LoadFromFile("New.xlsx");
                //Add a new worksheet and set its name
                Worksheet targetWorksheet = workbook2.Worksheets.Add("added");
                //Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet);
                //Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013);
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx");
    
            }
        }
    }
Imports Spire.Xls
    
    Namespace CopyExcelworksheet
    
        Class Program
    
            Private Shared Sub Main(ByVal args() As String)
                'Load the sample Excel and get the first worksheet
                Dim workbook As Workbook = New Workbook
                workbook.LoadFromFile("Sample.xlsx")
                Dim sheet As Worksheet = workbook.Worksheets(0)
                'Load the second Excel workbook
                Dim workbook2 As Workbook = New Workbook
                workbook2.LoadFromFile("New.xlsx")
                'Add a new worksheet and set its name
                Dim targetWorksheet As Worksheet = workbook2.Worksheets.Add("added")
                'Copy the original worksheet to the new added worksheets
                targetWorksheet.CopyFrom(sheet)
                'Save the Excel workbook.
                workbook2.SaveToFile("CopySheetBetweenWorkbooks.xlsx", FileFormat.Version2013)
                System.Diagnostics.Process.Start("CopySheetBetweenWorkbooks.xlsx")
            End Sub
        End Class
    End Namespace

C#/VB.NET: Copy Worksheets in Excel

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche