Installer avec Maven

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

Il existe de nombreuses raisons pour lesquelles vous devrez peut-être convertir des documents Word en images. Par exemple, de nombreux appareils peuvent ouvrir et afficher des images directement sans aucun logiciel spécial, et lorsque les images sont transmises, leur contenu est difficile à falsifier. Dans cet article, vous apprendrez comment convertir Word en formats d'image populaires tels que JPG, PNG et SVG en utilisant Spire.Doc for Java.

Installer Spire.Doc for Java

Tout d'abord, vous devez ajouter le fichier Spire.Doc.jar en tant que dépendance dans votre programme Java. Le fichier JAR peut être téléchargé à partir de ce lien. Si vous utilisez Maven, vous pouvez facilement importer le fichier JAR dans votre application en ajoutant le code suivant au fichier pom.xml de votre projet.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>14.2.4</version>
    </dependency>
</dependencies>

Convertir Word en JPG en Java

Spire.Doc for Java propose la méthode Document.saveToImages() pour convertir un document Word entier en images BufferedImage individuelles. Ensuite, chaque BufferedImage peut être enregistrée sous forme de fichier BMP, EMF, JPEG, PNG, GIF ou WMF. Voici les étapes pour convertir Word en JPG à l'aide de cette bibliothèque.

  • Créez un objet Document.
  • Chargez un document Word à l'aide de la méthode Document.loadFromFile().
  • Convertissez le document en images BufferedImage à l’aide de la méthode Document.saveToImages().
  • Parcourez la collection d’images pour obtenir celle spécifique.
  • Réécrivez l'image avec un espace colorimétrique différent.
  • Écrivez BufferedImage dans un fichier JPG.
  • Java
import com.spire.doc.Document;
    import com.spire.doc.documents.ImageType;
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    
    public class ConvertWordToJPG {
    
        public static void main(String[] args) throws IOException {
    
            //Create a Document object
            Document doc = new Document();
    
            //Load a Word document
            doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\ConvertTemplate.docx");
    
            //Convert the whole document into individual buffered images
            BufferedImage[] images = doc.saveToImages(ImageType.Bitmap);
    
            //Loop through the images
            for (int i = 0; i < images.length; i++) {
    
                //Get the specific image
                BufferedImage image = images[i];
    
                //Re-write the image with a different color space
                BufferedImage newImg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
                newImg.getGraphics().drawImage(image, 0, 0, null);
    
                //Write to a JPG file
                File file = new File("C:\\Users\\Administrator\\Desktop\\Images\\" + String.format(("Image-%d.jpg"), i));
                ImageIO.write(newImg, "JPEG", file);
            }
        }
    }

Convertir Word en SVG en Java

À l'aide de Spire.Doc for Java, vous pouvez enregistrer un document Word sous forme de liste de tableaux d'octets. Chaque tableau d'octets peut ensuite être écrit sous forme de fichier SVG. Les étapes détaillées pour convertir Word en SVG sont les suivantes.

  • Créez un objet Document.
  • Chargez un fichier Word à l'aide de la méthode Document.loadFromFile().
  • Enregistrez le document sous forme de liste de tableaux d'octets à l'aide de la méthode Document.saveToSVG().
  • Parcourez les éléments de la liste pour obtenir un tableau d’octets spécifique.
  • Écrivez le tableau d'octets dans un fichier SVG.
  • Java
import com.spire.doc.Document;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.List;
    
    public class ConvertWordToSVG {
    
        public static void main(String[] args) throws IOException {
    
            //Create a Document object
            Document doc = new Document();
    
            //Load a Word document
            doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\ConvertTemplate.docx");
    
            //Save the document as a list of byte arrays
            List<byte[]> svgBytes = doc.saveToSVG();
    
            //Loop through the items in the list
            for (int i = 0; i < svgBytes.size(); i++)
            {
                //Get a specific byte array
                byte[] byteArray = svgBytes.get(i);
    
                //Specify the output file name
                String outputFile = String.format("Image-%d.svg", i);
    
                //Write the byte array to a SVG file
                try (FileOutputStream stream = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\Images\\" + outputFile)) {
                    stream.write(byteArray);
                }
            }
        }
    }

Convertir Word en PNG avec une résolution personnalisée

Une image avec une résolution plus élevée est généralement plus claire. Vous pouvez personnaliser la résolution de l'image lors de la conversion de Word en PNG en suivant les étapes suivantes.

  • Créez un objet Document.
  • Chargez un fichier Word à l'aide de la méthode Document.loadFromFile().
  • Convertissez le document en images BufferedImage avec la résolution spécifiée à l'aide de la méthode Document.saveToImages().
  • Parcourez la collection d’images pour obtenir celle spécifique et enregistrez-la sous forme de fichier PNG.
  • Java
import com.spire.doc.Document;
    import com.spire.doc.documents.ImageType;
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    
    public class ConvertWordToPNG {
    
        public static void main(String[] args) throws IOException {
    
            //Create a Document object
            Document doc = new Document();
    
            //Load a Word document
            doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\ConvertTemplate.docx");
    
            //Convert the whole document into individual buffered images with customized resolution
            BufferedImage[] images = doc.saveToImages(0, doc.getPageCount(), ImageType.Bitmap, 150, 150);
    
            //Loop through the images
            for (int i = 0; i < images.length; i++) {
    
                //Get the specific image
                BufferedImage image = images[i];
    
                //Write to a PNG file
                File file = new File("C:\\Users\\Administrator\\Desktop\\Images\\" + String.format(("Image-%d.png"), i));
                ImageIO.write(image, "PNG", file);
            }
        }
    }

Java: Convert Word to Images (JPG, PNG and SVG)

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:49

C# Edit or Delete Comments in Excel

Installed via NuGet

PM> Install-Package Spire.XLS

Related Links

Excel comments are additional notes or commentary that can be added to specified cells to provide more in-depth explanations or to offer tips to other users. Once a comment’s been added, Excel provides users with the flexibility to format, edit, delete and show/hide the comment in the worksheet. In this article, you will learn how to programmatically edit or delete existing comments in Excel using Spire.XLS for .NET.

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.

PM> Install-Package Spire.XLS

Edit Comments in Excel

After adding comments to your Excel workbook, you may sometimes need to make changes to the added comments. The below table lists some of the core classes and properties used to get the existing comments and then set new text as well as formatting for the comments.

Name Description
CellRange.Comment Property Returns a Comment object that represents the comment associated with the cell in the upper-left corner of the range.
ExcelCommentObject Class Represents a comment.
ExcelCommentObject.Text Property Gets or sets the comment text.
ExcelCommentObject.Height Property Gets or sets height of a comment.
ExcelCommentObject.Width Property Gets or sets width of a comment.
ExcelCommentObject.AutoSize Property Indicates whether the size of the specified object is changed automatically to fit text within its boundaries.

The following are steps to edit comments in Excel:

  • Create a Workbook instance.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get the first worksheet of the Excel file using Workbook.Worksheets[] property.
  • Get a comment in a specific cell range using Worksheet.Range.Comment property.
  • Set new text and height/width or auto size for the existing comment using the properties of ExcelCommentObject class.
  • Save the document to another file using Workbook.SaveToFile() method.
  • 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

Delete Comments in Excel

The ExcelCommentObject.Remove() method offered by Spire.XLS for .NET allows you to remove a specified comment easily. The detailed steps are as follows:

  • Create a Workbook instance.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get the first worksheet of the Excel file using Workbook.Worksheets[] property.
  • Get a comment in a specific cell range using Worksheet.Range.Comment property and then delete the comment using ExcelCommentObject.Remove() method.
  • Save the document to another file using Workbook.SaveToFile() method.
  • 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

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:48

C# Editar ou excluir comentários no Excel

Instalado via NuGet

PM> Install-Package Spire.XLS

Links Relacionados

Os comentários do Excel são notas ou comentários adicionais que podem ser adicionados a células específicas para fornecer explicações mais aprofundadas ou para oferecer dicas a outros usuários. Depois que um comentário é adicionado, o Excel oferece aos usuários flexibilidade para formatar, editar, excluir e mostrar/ocultar o comentário na planilha. Neste artigo, você aprenderá como programar edite ou exclua comentários existentes no Excel usando Spire.XLS for .NET.

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.

PM> Install-Package Spire.XLS

Editar comentários no Excel

Depois de adicionar comentários à sua pasta de trabalho do Excel, às vezes você pode precisar fazer alterações nos comentários adicionados. A tabela abaixo lista algumas das principais classes e propriedades usadas para obter os comentários existentes e, em seguida, definir o novo texto, bem como a formatação dos comentários.

Nome Descrição
Propriedade CellRange.Comment Retorna um objeto Comment que representa o comentário associado à célula no canto superior esquerdo do intervalo.
Classe ExcelCommentObject Representa um comentário.
Propriedade ExcelCommentObject.Text Obtém ou define o texto do comentário.
Propriedade ExcelCommentObject.Height Obtém ou define a altura de um comentário.
Propriedade ExcelCommentObject.Width Obtém ou define a largura de um comentário.
Propriedade ExcelCommentObject.AutoSize Indica se o tamanho do objeto especificado é alterado automaticamente para ajustar o texto dentro de seus limites.

A seguir estão as etapas para editar comentários no Excel:

  • Crie uma instância de pasta de trabalho.
  • Carregue um arquivo Excel usando o método Workbook.LoadFromFile().
  • Obtenha a primeira planilha do arquivo Excel usando a propriedade Workbook.Worksheets[].
  • Obtenha um comentário em um intervalo de células específico usando a propriedade Worksheet.Range.Comment.
  • Defina o novo texto e altura/largura ou tamanho automático para o comentário existente usando as propriedades da classe ExcelCommentObject.
  • Salve o documento em outro arquivo usando o método 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

Excluir comentários no Excel

O método ExcelCommentObject.Remove() oferecido pelo Spire.XLS for .NET permite remover facilmente um comentário especificado. As etapas detalhadas são as seguintes:

  • Crie uma instância de pasta de trabalho.
  • Carregue um arquivo Excel usando o método Workbook.LoadFromFile().
  • Obtenha a primeira planilha do arquivo Excel usando a propriedade Workbook.Worksheets[].
  • Obtenha um comentário em um intervalo de células específico usando a propriedade Worksheet.Range.Comment e exclua o comentário usando o método ExcelCommentObject.Remove().
  • Salve o documento em outro arquivo usando o método 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

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

Установлено через NuGet

PM> Install-Package Spire.XLS

Ссылки по теме

Комментарии Excel — это дополнительные примечания или комментарии, которые можно добавлять к указанным ячейкам, чтобы предоставить более подробные пояснения или дать советы другим пользователям. После добавления комментария Excel предоставляет пользователям возможность форматировать, редактировать, удалять и показывать/скрывать комментарий на листе. В этой статье вы узнаете, как программно редактировать или удалять существующие комментарии в Excel с помощью Spire.XLS for .NET.

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

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

PM> Install-Package Spire.XLS

Редактировать комментарии в Excel

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

Имя Описание
Свойство CellRange.Comment Возвращает объект Comment, который представляет комментарий, связанный с ячейкой в верхнем левом углу диапазона.
Класс ExcelCommentObject Представляет комментарий.
Свойство ExcelCommentObject.Text Получает или задает текст комментария.
Свойство ExcelCommentObject.Height Получает или задает высоту комментария.
Свойство ExcelCommentObject.Width Получает или задает ширину комментария.
Свойство ExcelCommentObject.AutoSize Указывает, изменяется ли размер указанного объекта автоматически, чтобы текст помещался в его границах.

Ниже приведены шаги для редактирования комментариев в Excel:

  • Создайте экземпляр рабочей книги.
  • Загрузите файл Excel с помощью метода Workbook.LoadFromFile().
  • Получите первый лист файла Excel, используя свойство Workbook.Worksheets[].
  • Получите комментарий в определенном диапазоне ячеек, используя свойство 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

Метод ExcelCommentObject.Remove(), предлагаемый Spire.XLS for .NET, позволяет легко удалить указанный комментарий. Подробные шаги следующие:

  • Создайте экземпляр рабочей книги.
  • Загрузите файл Excel с помощью метода Workbook.LoadFromFile().
  • Получите первый лист файла Excel, используя свойство Workbook.Worksheets[].
  • Получите комментарий в определенном диапазоне ячеек, используя свойство 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-дневную пробную лицензию для себя.

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

Über NuGet installiert

PM> Install-Package Spire.XLS

verwandte Links

Excel-Kommentare sind zusätzliche Notizen oder Kommentare, die zu bestimmten Zellen hinzugefügt werden können, um tiefergehende Erklärungen zu geben oder anderen Benutzern Tipps zu geben. Sobald ein Kommentar hinzugefügt wurde, bietet Excel Benutzern die Flexibilität, den Kommentar im Arbeitsblatt zu formatieren, zu bearbeiten, zu löschen und ein-/auszublenden. In diesem Artikel erfahren Sie, wie Sie programmgesteuert vorgehen Bearbeiten oder löschen Sie vorhandene Kommentare in Excel mit Spire.XLS for .NET.

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.

PM> Install-Package Spire.XLS

Bearbeiten Sie Kommentare in Excel

Nachdem Sie Kommentare zu Ihrer Excel-Arbeitsmappe hinzugefügt haben, müssen Sie möglicherweise manchmal Änderungen an den hinzugefügten Kommentaren vornehmen. Die folgende Tabelle listet einige der Kernklassen und Eigenschaften auf, die verwendet werden, um die vorhandenen Kommentare abzurufen und dann neuen Text sowie die Formatierung für die Kommentare festzulegen.

Name Beschreibung
CellRange.Comment-Eigenschaft Gibt ein Comment-Objekt zurück, das den Kommentar darstellt, der der Zelle in der oberen linken Ecke des Bereichs zugeordnet ist.
ExcelCommentObject-Klasse Stellt einen Kommentar dar.
ExcelCommentObject.Text-Eigenschaft Ruft den Kommentartext ab oder legt ihn fest.
ExcelCommentObject.Height-Eigenschaft Ruft die Höhe eines Kommentars ab oder legt diese fest.
ExcelCommentObject.Width-Eigenschaft Ruft die Breite eines Kommentars ab oder legt diese fest.
ExcelCommentObject.AutoSize-Eigenschaft Gibt an, ob die Größe des angegebenen Objekts automatisch geändert wird, um den Text innerhalb seiner Grenzen anzupassen.

Im Folgenden finden Sie die Schritte zum Bearbeiten von Kommentaren in Excel:

  • Erstellen Sie eine Arbeitsmappeninstanz.
  • Laden Sie eine Excel-Datei mit der Methode Workbook.LoadFromFile().
  • Rufen Sie das erste Arbeitsblatt der Excel-Datei mit der Eigenschaft Workbook.Worksheets[] ab.
  • Rufen Sie mit der Eigenschaft Worksheet.Range.Comment einen Kommentar in einem bestimmten Zellbereich ab.
  • Legen Sie mithilfe der Eigenschaften der ExcelCommentObject-Klasse neuen Text und Höhe/Breite oder automatische Größe für den vorhandenen Kommentar fest.
  • Speichern Sie das Dokument mit der Methode Workbook.SaveToFile() in einer anderen Datei.
  • 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

Kommentare in Excel löschen

Mit der von Spire.XLS for .NET angebotenen Methode ExcelCommentObject.Remove() können Sie einen bestimmten Kommentar einfach entfernen. Die detaillierten Schritte sind wie folgt:

  • Erstellen Sie eine Arbeitsmappeninstanz.
  • Laden Sie eine Excel-Datei mit der Methode Workbook.LoadFromFile().
  • Rufen Sie das erste Arbeitsblatt der Excel-Datei mit der Eigenschaft Workbook.Worksheets[] ab.
  • Rufen Sie mit der Eigenschaft Worksheet.Range.Comment einen Kommentar in einem bestimmten Zellbereich ab und löschen Sie den Kommentar dann mit der Methode ExcelCommentObject.Remove().
  • Speichern Sie das Dokument mit der Methode Workbook.SaveToFile() in einer anderen Datei.
  • 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

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:45

C# Editar o eliminar comentarios en Excel

Instalado a través de NuGet

PM> Install-Package Spire.XLS

enlaces relacionados

Los comentarios de Excel son notas o comentarios adicionales que se pueden agregar a celdas específicas para proporcionar explicaciones más detalladas u ofrecer sugerencias a otros usuarios. Una vez que se ha agregado un comentario, Excel brinda a los usuarios la flexibilidad de formatear,editar,eliminar y mostrar/ocultar el comentario en la hoja de trabajo. En este artículo, aprenderá cómo programar edite o elimine comentarios existentes en Excel usando Spire.XLS for .NET.

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.

PM> Install-Package Spire.XLS

Editar comentarios en Excel

Después de agregar comentarios a su libro de Excel, es posible que en ocasiones necesite realizar cambios en los comentarios agregados. La siguiente tabla enumera algunas de las clases y propiedades principales utilizadas para obtener los comentarios existentes y luego establecer texto nuevo y formato para los comentarios.

Nombre Descripción
CellRange.Comment Propiedad Devuelve un objeto Comentario que representa el comentario asociado con la celda en la esquina superior izquierda del rango.
Clase ExcelCommentObject Representa un comentario.
Propiedad ExcelCommentObject.Text Obtiene o establece el texto del comentario.
Propiedad ExcelCommentObject.Height Obtiene o establece la altura de un comentario.
Propiedad ExcelCommentObject.Width Obtiene o establece el ancho de un comentario.
Propiedad ExcelCommentObject.AutoSize Indica si el tamaño del objeto especificado se cambia automáticamente para ajustar el texto dentro de sus límites.

Los siguientes son pasos para editar comentarios en Excel:

  • Cree una instancia de libro de trabajo.
  • Cargue un archivo de Excel usando el método Workbook.LoadFromFile().
  • Obtenga la primera hoja de trabajo del archivo de Excel usando la propiedad Workbook.Worksheets[].
  • Obtenga un comentario en un rango de celdas específico usando la propiedad Worksheet.Range.Comment.
  • Establezca un nuevo texto y alto/ancho o tamaño automático para el comentario existente utilizando las propiedades de la clase ExcelCommentObject.
  • Guarde el documento en otro archivo utilizando el método 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

Eliminar comentarios en Excel

El método ExcelCommentObject.Remove() ofrecido por Spire.XLS for .NET le permite eliminar fácilmente un comentario específico. Los pasos detallados son los siguientes:

  • Cree una instancia de libro de trabajo.
  • Cargue un archivo de Excel usando el método Workbook.LoadFromFile().
  • Obtenga la primera hoja de trabajo del archivo de Excel usando la propiedad Workbook.Worksheets[].
  • Obtenga un comentario en un rango de celdas específico usando la propiedad Worksheet.Range.Comment y luego elimine el comentario usando el método ExcelCommentObject.Remove().
  • Guarde el documento en otro archivo utilizando el método 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

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: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