zoukankan      html  css  js  c++  java
  • Xamarin.Forms 导出Excel

    导入NuGet里的DocumentFormat.OpenXml

    添加数据

    public static async System.Threading.Tasks.Task<string> ExportDataToExcelAsync(HistoricalDataListViewModel viewModel, string fileName)        {
                string path = "";
                if (viewModel == null) return "";
                // Granted storage permission
                var storageStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
    
                if (storageStatus != PermissionStatus.Granted)
                {
                    var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Storage });
                    storageStatus = results[Permission.Storage];
                }
    
                if (viewModel.Datas.Count > 0)
                {
                    try
                    {
                        path = DependencyService.Get<IExportFilesToLocation>().GetFolderLocation() + fileName + ".xlsx";
                        using (SpreadsheetDocument document = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook))
                        {
                            WorkbookPart workbookPart = document.AddWorkbookPart();
                            workbookPart.Workbook = new Workbook();
    
                            WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                            worksheetPart.Worksheet = new Worksheet();
                            Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
                            Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "数据列表" };
                            sheets.Append(sheet);
    
                            #region 样式
                            WorkbookStylesPart stylepart = workbookPart.AddNewPart<WorkbookStylesPart>();
    
                            stylepart.Stylesheet = new Stylesheet();
    
                            SetStyle(stylepart);
                            #endregion
    
                            workbookPart.Workbook.Save();
    
                            Columns columns = new Columns();
                            columns.AppendChild(new Column()
                            {
                                Min = 1,
                                Max = (UInt32)viewModel.Datas.First().ModelList.Count(x => x.IsVisibility),
                                CustomWidth = true,
                                Width = (DoubleValue)20
                            });
                            worksheetPart.Worksheet.Append(columns);
    
                            SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
                            // Constructing header
                            Row row = new Row();
                            row.Append(viewModel.Datas.First().ModelList.Where(x=>x.IsVisibility).OrderBy(x=>x.OrderId).Select(x =>
                            new DocumentFormat.OpenXml.Spreadsheet.Cell()
                            {
                                CellValue = new CellValue(x.ChineseName+(String.IsNullOrEmpty(x.Unit)?"":String.Format("({0})",x.Unit))),
                                DataType = new EnumValue<CellValues>(CellValues.String),
                                StyleIndex = 3
                            }));
    
                            // Insert the header row to the Sheet Data
                            sheetData.AppendChild(row);
    
                            // Add each product
                            foreach (var d in viewModel.Datas)
                            {
                                row = new Row();
                                row.Append(d.ModelList.Where(x => x.IsVisibility).OrderBy(x => x.OrderId).Select(x =>
                                    new DocumentFormat.OpenXml.Spreadsheet.Cell()
                                    {
                                        CellValue = new CellValue(x.Display),
                                        DataType = new EnumValue<CellValues>((x.DataType == 0 && x.Name != "nDate") ? CellValues.Number : CellValues.String),
                                        StyleIndex = 3
                                    }));
                                sheetData.AppendChild(row);
                            }
                            worksheetPart.Worksheet.Save();
                        }
                    }
                    catch (Exception ex)
                    {
                        Xamarin.Forms.MessagingCenter.Send<SystemLog>(new SystemLog() { Type = "错误信息", Log = ex.ToString(), Time = DateTime.Now }, "SystemLog");
                        path = "";
    
                    }
                }
                return path;
    
            }

    设置样式(字体大小 居中等)

            private static void SetStyle(WorkbookStylesPart stylesPart)
            {
                //添加SheetStyle:FontBorderFill字体居中
                Fonts fonts = new Fonts() { Count = (UInt32Value)2U, KnownFonts = true };
                //fontId = 0
                DocumentFormat.OpenXml.Spreadsheet.Font font = new DocumentFormat.OpenXml.Spreadsheet.Font();
                DocumentFormat.OpenXml.Spreadsheet.FontSize fontSize = new DocumentFormat.OpenXml.Spreadsheet.FontSize() { Val = 12D };
                FontFamilyNumbering fontFamilyNumbering = new FontFamilyNumbering() { Val = 1 };
                FontScheme fontScheme = new FontScheme() { Val = FontSchemeValues.Minor };
                font.Append(fontSize);
                font.Append(fontFamilyNumbering);
                font.Append(fontScheme);
                fonts.Append(font);
                //fontId = 1
                font = new DocumentFormat.OpenXml.Spreadsheet.Font();
                Bold bold = new Bold();
                fontSize = new DocumentFormat.OpenXml.Spreadsheet.FontSize() { Val = 26D };
                fontFamilyNumbering = new FontFamilyNumbering() { Val = 1 };
                fontScheme = new FontScheme() { Val = FontSchemeValues.Minor };
                font.Append(bold);
                font.Append(fontSize);
                font.Append(fontFamilyNumbering);
                font.Append(fontScheme);
                fonts.Append(font);
                stylesPart.Stylesheet.Append(fonts);
    
                Fills fills = new Fills() { Count = (UInt32Value)3U };
                //FillId = 0
                Fill fill = new Fill();
                PatternFill patternFill = new PatternFill() { PatternType = PatternValues.None };
                fill.Append(patternFill);
                fills.Append(fill);
                //FillId = 1
                fill = new Fill();
                patternFill = new PatternFill() { PatternType = PatternValues.Gray125 };
                fill.Append(patternFill);
                fills.Append(fill);
                //FillId = 2
                fill = new Fill();
                patternFill = new PatternFill() { PatternType = PatternValues.Solid };
                ForegroundColor foregroundColor = new ForegroundColor() { Rgb = "FF87ceeb" };
                BackgroundColor backgroundColor = new BackgroundColor() { Indexed = (UInt32Value)64U };
                patternFill.Append(foregroundColor);
                patternFill.Append(backgroundColor);
                fill.Append(patternFill);
                fills.Append(fill);
                stylesPart.Stylesheet.Append(fills);
    
                Borders borders = new Borders() { Count = (UInt32Value)2U };
                //BorderId = 0
                Border border = new Border();
                LeftBorder leftBorder = new LeftBorder();
                RightBorder rightBorder = new RightBorder();
                TopBorder topBorder = new TopBorder();
                BottomBorder bottomBorder = new BottomBorder();
                DiagonalBorder diagonalBorder = new DiagonalBorder();
                border.Append(leftBorder);
                border.Append(rightBorder);
                border.Append(topBorder);
                border.Append(bottomBorder);
                border.Append(diagonalBorder);
                borders.Append(border);
                //BorderId = 1
                border = new Border();
                leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
                rightBorder = new RightBorder() { Style = BorderStyleValues.Thin };
                topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
                bottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin };
                DocumentFormat.OpenXml.Spreadsheet.Color color = new DocumentFormat.OpenXml.Spreadsheet.Color() { Indexed = (UInt32Value)64U };
                leftBorder.Append(color);
                color = new DocumentFormat.OpenXml.Spreadsheet.Color() { Indexed = (UInt32Value)64U };
                rightBorder.Append(color);
                color = new DocumentFormat.OpenXml.Spreadsheet.Color() { Indexed = (UInt32Value)64U };
                topBorder.Append(color);
                color = new DocumentFormat.OpenXml.Spreadsheet.Color() { Indexed = (UInt32Value)64U };
                bottomBorder.Append(color);
                diagonalBorder = new DiagonalBorder();
                border.Append(leftBorder);
                border.Append(rightBorder);
                border.Append(topBorder);
                border.Append(bottomBorder);
                border.Append(diagonalBorder);
                borders.Append(border);
                stylesPart.Stylesheet.Append(borders);
    
                //StyleIndex = 0;
                CellFormats cellFormats = new CellFormats() { Count = (UInt32Value)5U };
                CellFormat cellFormat = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U };
                Alignment alignment = new Alignment() { Vertical = VerticalAlignmentValues.Center };
                cellFormat.Append(alignment);
                cellFormats.Append(cellFormat);
                //StyleIndex = 1;
                cellFormat = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)2U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyFont = true, ApplyFill = true, ApplyBorder = true, ApplyAlignment = true };
                alignment = new Alignment() { Vertical = VerticalAlignmentValues.Center };
                cellFormat.Append(alignment);
                cellFormats.Append(cellFormat);
                //StyleIndex = 2;
                cellFormat = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)1U, FillId = (UInt32Value)2U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyFont = true, ApplyFill = true, ApplyBorder = true, ApplyAlignment = true };
                alignment = new Alignment() { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center };
                cellFormat.Append(alignment);
                cellFormats.Append(cellFormat);
                //StyleIndex = 3;
                cellFormat = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0, BorderId = (UInt32Value)1U, FormatId = (UInt32Value)0U, ApplyFont = true, ApplyFill = true, ApplyBorder = true, ApplyAlignment = true };
                alignment = new Alignment() { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center };
                cellFormat.Append(alignment);
                cellFormats.Append(cellFormat);
                //StyleIndex = 4;
                cellFormat = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyFont = true, ApplyFill = true, ApplyBorder = true, ApplyAlignment = true };
                cellFormats.Append(cellFormat);
    
                stylesPart.Stylesheet.Append(cellFormats);
    
                stylesPart.Stylesheet.Save();
            }
  • 相关阅读:
    [MacOS]Sublime text3 安装(一)
    [RHEL8]开启BBR
    PAT Advanced 1136 A Delayed Palindrome (20分)
    PAT Advanced 1144 The Missing Number (20分)
    PAT Advanced 1041 Be Unique (20分)
    PAT Advanced 1025 PAT Ranking (25分)
    PAT Advanced 1022 Digital Library (30分)
    PAT Advanced 1019 General Palindromic Number (20分)
    PAT Advanced 1011 World Cup Betting (20分)
    PAT Advanced 1102 Invert a Binary Tree (25分)
  • 原文地址:https://www.cnblogs.com/Xamarin-Oz/p/12625613.html
Copyright © 2011-2022 走看看