如何使用 Excel 对象将 DataGridView 数据导出到 Excel

2021-05-04 18:26

阅读:719

标签:ring   try   帮助   vps   pack   客户   filename   论坛   form   

转载出处:https://code.msdn.microsoft.com/How-to-insert-image-into-93964561

本项目阐述如何使用 Open XML SDK 将图像插入到 Excel 中

简介

本示例演示如何使用 Open XML SDK 将图像自动插入到电子表格中。一些客户经常在 MSDN 论坛上咨询此问题,但是 MSDN 上并不存在示例。因此,如果 MSDN 中存在此示例,客户将可以从此示例中获取帮助。

客户证明:

http://social.msdn.microsoft.com/Forums/zh-CN/oxmlsdk/thread/4c369c2f-72ed-4e86-9c62-ff606d29ace2

http://social.msdn.microsoft.com/Forums/zh-CN/oxmlsdk/thread/5c60076e-9884-4298-a443-c97d941cf09d

http://stackoverflow.com/questions/5793950/c-sharp-openxml-insert-an-image-into-an-excel-document

生成项目

在 Visual Studio 2013 中打开项目 (InsertImageIntoExcel.csproj) 并生成项目。

class Utility 
    { 
        public static void CreatePackage(string sFile, string imageFileName) 
        { 
            try 
            { 
                // Create a spreadsheet document by supplying the filepath. 
                SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(sFile, SpreadsheetDocumentType.Workbook); 
 
                // Add a WorkbookPart to the document. 
                WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart(); 
                workbookpart.Workbook = new Workbook(); 
 
                // Add a WorksheetPart to the WorkbookPart. 
                WorksheetPart worksheetPart = workbookpart.AddNewPart(); 
                worksheetPart.Worksheet = new Worksheet(new SheetData()); 
 
                // Add Sheets to the Workbook. 
                Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets()); 
 
                // Append a new worksheet and associate it with the workbook. 
                Sheet sheet = new Sheet() 
                { 
                    Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), 
                    SheetId = 1, 
                    Name = "mySheet" 
                }; 
                sheets.Append(sheet); 
 
                var drawingsPart = worksheetPart.AddNewPart(); 
 
                if (!worksheetPart.Worksheet.ChildElements.OfType().Any()) 
                { 
                    worksheetPart.Worksheet.Append(new Drawing { Id = worksheetPart.GetIdOfPart(drawingsPart) }); 
                } 
 
                if (drawingsPart.WorksheetDrawing == null) 
                { 
                    drawingsPart.WorksheetDrawing = new WorksheetDrawing(); 
                } 
 
                var worksheetDrawing = drawingsPart.WorksheetDrawing; 
 
                var imagePart = drawingsPart.AddImagePart(ImagePartType.Jpeg); 
 
                using (var stream = new FileStream(imageFileName, FileMode.Open)) 
                { 
                    imagePart.FeedData(stream); 
                } 
 
                Bitmap bm = new Bitmap(imageFileName); 
                DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents(); 
                var extentsCx = (long)bm.Width * (long)((float)914400 / bm.HorizontalResolution); 
                var extentsCy = (long)bm.Height * (long)((float)914400 / bm.VerticalResolution); 
                bm.Dispose(); 
 
                var colOffset = 0; 
                var rowOffset = 0; 
                int colNumber = 5; 
                int rowNumber = 10; 
 
                var nvps = worksheetDrawing.Descendants(); 
                var nvpId = nvps.Count() > 0 ? 
                    (UInt32Value)worksheetDrawing.Descendants().Max(p => p.Id.Value) + 1 : 
                    1U; 
 
                var oneCellAnchor = new Xdr.OneCellAnchor( 
                    new Xdr.FromMarker 
                    { 
                        ColumnId = new Xdr.ColumnId((colNumber - 1).ToString()), 
                        RowId = new Xdr.RowId((rowNumber - 1).ToString()), 
                        ColumnOffset = new Xdr.ColumnOffset(colOffset.ToString()), 
                        RowOffset = new Xdr.RowOffset(rowOffset.ToString()) 
                    }, 
                    new Xdr.Extent { Cx = extentsCx, Cy = extentsCy }, 
                    new Xdr.Picture( 
                        new Xdr.NonVisualPictureProperties( 
                            new Xdr.NonVisualDrawingProperties { Id = nvpId, Name = "Picture " + nvpId, Description = imageFileName }, 
                            new Xdr.NonVisualPictureDrawingProperties(new A.PictureLocks { NoChangeAspect = true }) 
                        ), 
                        new Xdr.BlipFill( 
                            new A.Blip { Embed = drawingsPart.GetIdOfPart(imagePart), CompressionState = A.BlipCompressionValues.Print }, 
                            new A.Stretch(new A.FillRectangle()) 
                        ), 
                        new Xdr.ShapeProperties( 
                            new A.Transform2D( 
                                new A.Offset { X = 0, Y = 0 }, 
                                new A.Extents { Cx = extentsCx, Cy = extentsCy } 
                            ), 
                            new A.PresetGeometry { Preset = A.ShapeTypeValues.Rectangle } 
                        ) 
                    ), 
                    new Xdr.ClientData() 
                ); 
 
                worksheetDrawing.Append(oneCellAnchor); 
 
                workbookpart.Workbook.Save(); 
 
                // Close the document. 
                spreadsheetDocument.Close(); 
            } 
            catch (Exception ex) 
            { 
                Console.WriteLine(ex.Message); 
            } 
        } 
    } 

运行示例

  1. 本示例使用 Open XML SDK 将图像插入到 Excel 文件中。
  2. 将图像文件 SampleImage.jpg 从项目位置复制到可执行文件位置。
  3. 运行可执行文件‘InsertImageIntoExcel.exe’。此操作将创建一个名为‘InsertImage .xlsx’的 Excel 文件并将指定的图像插入到新工作表中。
  4. 打开 Excel 文件 InsertImage.xlsx 并验证内容

从项目中复制出来的代码:

 Program.cs文件中的代码

//****************************** Module Header ******************************//Module Name:    Program.cs
//Project:        InsertImageIntoExcel
//Copyright (c) Microsoft Corporation

//The project illustrates how to insert image into Excel using Open XML SDK

//This source is subject to the Microsoft Public License.
//See http://www.microsoft.com/en-us/openness/resources/licenses.aspx#MPL.
//All other rights reserved.

//*****************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Drawing;

namespace InsertImageIntoExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string appPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                string sFile = appPath + "\\InsertImage.xlsx";

                string imageFile = appPath + "\\SampleImage.jpg";

                // If the file exists, delete it
                if (File.Exists(sFile))
                {
                    File.Delete(sFile);
                }

                Utility.CreatePackage(sFile, imageFile);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

 Utility.cs中的代码

//****************************** Module Header ******************************//Module Name:    Utility.cs
//Project:        InsertImageIntoExcel
//Copyright (c) Microsoft Corporation

//The project illustrates how to insert image into Excel using Open XML SDK

//This source is subject to the Microsoft Public License.
//See http://www.microsoft.com/en-us/openness/resources/licenses.aspx#MPL.
//All other rights reserved.

//*****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using Xdr = DocumentFormat.OpenXml.Drawing.Spreadsheet;
using A = DocumentFormat.OpenXml.Drawing;
using System.Drawing;

namespace InsertImageIntoExcel
{
    class Utility
    {
        public static void CreatePackage(string sFile, string imageFileName)
        {
            try
            {
                // Create a spreadsheet document by supplying the filepath.
                SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(sFile, SpreadsheetDocumentType.Workbook);

                // Add a WorkbookPart to the document.
                WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
                workbookpart.Workbook = new Workbook();

                // Add a WorksheetPart to the WorkbookPart.
                WorksheetPart worksheetPart = workbookpart.AddNewPart();
                worksheetPart.Worksheet = new Worksheet(new SheetData());

                // Add Sheets to the Workbook.
                Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
                    AppendChild(new Sheets());

                // Append a new worksheet and associate it with the workbook.
                Sheet sheet = new Sheet()
                {
                    Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
                    SheetId = 1,
                    Name = "mySheet"
                };
                sheets.Append(sheet);

                var drawingsPart = worksheetPart.AddNewPart();

                if (!worksheetPart.Worksheet.ChildElements.OfType().Any())
                {
                    worksheetPart.Worksheet.Append(new Drawing { Id = worksheetPart.GetIdOfPart(drawingsPart) });
                }

                if (drawingsPart.WorksheetDrawing == null)
                {
                    drawingsPart.WorksheetDrawing = new WorksheetDrawing();
                }

                var worksheetDrawing = drawingsPart.WorksheetDrawing;

                var imagePart = drawingsPart.AddImagePart(ImagePartType.Jpeg);

                using (var stream = new FileStream(imageFileName, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }

                Bitmap bm = new Bitmap(imageFileName);
                DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
                var extentsCx = (long)bm.Width * (long)((float)914400 / bm.HorizontalResolution);
                var extentsCy = (long)bm.Height * (long)((float)914400 / bm.VerticalResolution);
                bm.Dispose();

                var colOffset = 0;
                var rowOffset = 0;
                int colNumber = 5;
                int rowNumber = 10;

                var nvps = worksheetDrawing.Descendants();
                var nvpId = nvps.Count() > 0 ?
                    (UInt32Value)worksheetDrawing.Descendants().Max(p => p.Id.Value) + 1 :
                    1U;

                var oneCellAnchor = new Xdr.OneCellAnchor(
                    new Xdr.FromMarker
                    {
                        ColumnId = new Xdr.ColumnId((colNumber - 1).ToString()),
                        RowId = new Xdr.RowId((rowNumber - 1).ToString()),
                        ColumnOffset = new Xdr.ColumnOffset(colOffset.ToString()),
                        RowOffset = new Xdr.RowOffset(rowOffset.ToString())
                    },
                    new Xdr.Extent { Cx = extentsCx, Cy = extentsCy },
                    new Xdr.Picture(
                        new Xdr.NonVisualPictureProperties(
                            new Xdr.NonVisualDrawingProperties { Id = nvpId, Name = "Picture " + nvpId, Description = imageFileName },
                            new Xdr.NonVisualPictureDrawingProperties(new A.PictureLocks { NoChangeAspect = true })
                        ),
                        new Xdr.BlipFill(
                            new A.Blip { Embed = drawingsPart.GetIdOfPart(imagePart), CompressionState = A.BlipCompressionValues.Print },
                            new A.Stretch(new A.FillRectangle())
                        ),
                        new Xdr.ShapeProperties(
                            new A.Transform2D(
                                new A.Offset { X = 0, Y = 0 },
                                new A.Extents { Cx = extentsCx, Cy = extentsCy }
                            ),
                            new A.PresetGeometry { Preset = A.ShapeTypeValues.Rectangle }
                        )
                    ),
                    new Xdr.ClientData()
                );

                worksheetDrawing.Append(oneCellAnchor);

                workbookpart.Workbook.Save();

                // Close the document.
                spreadsheetDocument.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

 

如何使用 Excel 对象将 DataGridView 数据导出到 Excel

标签:ring   try   帮助   vps   pack   客户   filename   论坛   form   

原文地址:http://www.cnblogs.com/xiehaofeng/p/7701083.html


评论


亲,登录后才可以留言!