简体   繁体   English

如何将datagridview导出到excel

[英]how to export datagridview into excel

How do I fix the error System.InvalidCastException ?如何修复错误System.InvalidCastException I don't find the solution, if I change the code with another code but the errors still same System.InvalidCastException :我找不到解决方案,如果我用另一个代码更改代码但错误仍然相同System.InvalidCastException

Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
worksheet = workbook.ActiveSheet;
worksheet.Name = "RekapPerangkatZTE";

for (int i = 1; i < dgvperangkat.Columns.Count + 1; i++)
{
    worksheet.Cells[i, 1] = dgvperangkat.Columns[i - 1].HeaderText;
}

for (int i = 0; i < dgvperangkat.Rows.Count; i++)
{
    for (int j = 0; j < dgvperangkat.Columns.Count; j++)
    {
        worksheet.Cells[i + 2, j + 1] = dgvperangkat.Rows[i].Cells[j].Value.ToString();   
    }
}

var saveFileDialoge = new SaveFileDialog();
saveFileDialoge.FileName = "output";
saveFileDialoge.DefaultExt = ".xlsx";
if (saveFileDialoge.ShowDialog() == DialogResult.OK)
{
    workbook.SaveAs(saveFileDialoge.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
app.Quit();

you can use EPPlus .您可以使用EPPlus Fistly add your solution a helper class, that's name can be helper.cs, add static method ExportToExcel method.首先为您的解决方案添加一个帮助器类,其名称可以是 helper.cs,添加静态方法 ExportToExcel 方法。 if you want to use in another code block, only you can call this methods.如果你想在另一个代码块中使用,只有你可以调用这个方法。

System.InvalidCastException may be can be caused your data. System.InvalidCastException 可能会导致您的数据。 I sent detailed code for your solutions, only call ExportToExcel method with datatable, directory info and file name, i hope it will be fix your problem.我为您的解决方案发送了详细的代码,只调用带有数据表、目录信息和文件名的 ExportToExcel 方法,我希望它能解决您的问题。 Dont forget adding EPPlus library on references.不要忘记在引用上添加 EPPlus 库。 It's works all datatables, that is flexable all data.它适用于所有数据表,即所有数据都是灵活的。

EPPlus 参考 EPPlus 使用线

//Usage example code
  DataTable table = new DataTable(); //Get or set your data to DataTable
  table = db.SampleResult.ToDataTable(); // This is sample, your data result can be here and it's must be datatable
  DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Upload/ExportedFiles"));
  string fileName = "Sample_List;
  Helpers.ExportToExcel(table, di, fileName);

-Helper.cs -Helper.cs

//Usings
using System.IO;
using OfficeOpenXml;
Using OfficeOpenXml.Style;

public static string ExportToExcel(DataTable dt, DirectoryInfo outputDir, string fileName)
    {
        FileInfo newFile = new FileInfo(outputDir.FullName + @"\" + fileName + ".xlsx");
        string ReportName = "Sample Report";
        // If any file exists in this directory having name 'Sample1.xlsx', then delete it
        if (newFile.Exists)
        {
            //If you want to delete OR rename
            //newFile.Delete(); // ensures we create a new workbook
            //Random rnd = new Random();
            //string random = rnd.Next(100, 999).ToString();
            //newFile = new FileInfo(outputDir.FullName + @"\" + fileName + random + ".xlsx");
        }
        using (ExcelPackage package = new ExcelPackage(newFile))
        {
            // Add a worksheet to the empty workbook
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(ReportName);
            worksheet.Row(1).Height = 20;


            int columnCount = dt.Columns.Count;


            // Add the headers
            worksheet.Cells[1, 1, 1, columnCount].Merge = true;
            worksheet.Cells[1, 1].Value = fileName + " Sample List Title - " + DateTime.Now.ToShortDateString();
            worksheet.Cells[1, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            worksheet.Cells[1, 1].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
            worksheet.Cells[1, 1].Style.Font.Size = 15;
            worksheet.Cells[1, 1].Style.Font.Bold = true;

            int intColumn = 1;

            foreach (DataColumn column in dt.Columns)
            {
                worksheet.Cells[2, intColumn].Value = column.ColumnName;

            string[] alphabet = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ", "CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM", "CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ", "DA", "DB", "DC", "DD", "DE", "DF", "DG", "DH", "DI", "DJ", "DK", "DL", "DM", "DN", "DO", "DP", "DQ", "DR", "DS", "DT", "DU", "DV", "DW", "DX", "DY", "DZ", "EA", "EB", "EC", "ED", "EE", "EF", "EG", "EH", "EI", "EJ", "EK", "EL", "EM", "EN", "EO", "EP", "EQ", "ER", "ES", "ET", "EU", "EV", "EW", "EX", "EY", "EZ", "FA", "FB", "FC", "FD", "FE", "FF", "FG", "FH", "FI", "FJ", "FK", "FL", "FM", "FN", "FO", "FP", "FQ", "FR", "FS", "FT", "FU", "FV", "FW", "FX", "FY", "FZ", "GA", "GB", "GC", "GD", "GE", "GF", "GG", "GH", "GI", "GJ", "GK", "GL", "GM", "GN", "GO", "GP", "GQ", "GR", "GS", "GT", "GU", "GV", "GW", "GX", "GY", "GZ", "HA", "HB", "HC", "HD", "HE", "HF", "HG", "HH", "HI", "HJ", "HK", "HL", "HM", "HN", "HO", "HP", "HQ", "HR", "HS", "HT", "HU", "HV", "HW", "HX", "HY", "HZ", "IA", "IB", "IC", "ID", "IE", "IF", "IG", "IH", "II", "IJ", "IK", "IL", "IM", "IN", "IO", "IP", "IQ", "IR", "IS", "IT", "IU", "IV", "IW", "IX", "IY", "IZ", "JA", "JB", "JC", "JD", "JE", "JF", "JG", "JH", "JI", "JJ", "JK", "JL", "JM", "JN", "JO", "JP", "JQ", "JR", "JS", "JT", "JU", "JV", "JW", "JX", "JY", "JZ", "KA", "KB", "KC", "KD", "KE", "KF", "KG", "KH", "KI", "KJ", "KK", "KL", "KM", "KN", "KO", "KP", "KQ", "KR", "KS", "KT", "KU", "KV", "KW", "KX", "KY", "KZ", "LA", "LB", "LC", "LD", "LE", "LF", "LG", "LH", "LI", "LJ", "LK", "LL", "LM", "LN", "LO", "LP", "LQ", "LR", "LS", "LT", "LU", "LV", "LW", "LX", "LY", "LZ", "MA", "MB", "MC", "MD", "ME", "MF", "MG", "MH", "MI", "MJ", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NB", "NC", "ND", "NE", "NF", "NG", "NH", "NI", "NJ", "NK", "NL", "NM", "NN", "NO", "NP", "NQ", "NR", "NS", "NT", "NU", "NV", "NW", "NX", "NY", "NZ", "OA", "OB", "OC", "OD", "OE", "OF", "OG", "OH", "OI", "OJ", "OK", "OL", "OM", "ON", "OO", "OP", "OQ", "OR", "OS", "OT", "OU", "OV", "OW", "OX", "OY", "OZ", "PA", "PB", "PC", "PD", "PE", "PF", "PG", "PH", "PI", "PJ", "PK", "PL", "PM", "PN", "PO", "PP", "PQ", "PR", "PS", "PT", "PU", "PV", "PW", "PX", "PY", "PZ", "QA", "QB", "QC", "QD", "QE", "QF", "QG", "QH", "QI", "QJ", "QK", "QL", "QM", "QN", "QO", "QP", "QQ", "QR", "QS", "QT", "QU", "QV", "QW", "QX", "QY", "QZ", "RA", "RB", "RC", "RD", "RE", "RF", "RG", "RH", "RI", "RJ", "RK", "RL", "RM", "RN", "RO", "RP", "RQ", "RR", "RS", "RT", "RU", "RV", "RW", "RX", "RY", "RZ", "SA", "SB", "SC", "SD", "SE", "SF", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SP", "SQ", "SR", "SS", "ST", "SU", "SV", "SW", "SX", "SY", "SZ", "TA", "TB", "TC", "TD", "TE", "TF", "TG", "TH", "TI", "TJ", "TK", "TL", "TM", "TN", "TO", "TP", "TQ", "TR", "TS", "TT", "TU", "TV", "TW", "TX", "TY", "TZ", "UA", "UB", "UC", "UD", "UE", "UF", "UG", "UH", "UI", "UJ", "UK", "UL", "UM", "UN", "UO", "UP", "UQ", "UR", "US", "UT", "UU", "UV", "UW", "UX", "UY", "UZ", "VA", "VB", "VC", "VD", "VE", "VF", "VG", "VH", "VI", "VJ", "VK", "VL", "VM", "VN", "VO", "VP", "VQ", "VR", "VS", "VT", "VU", "VV", "VW", "VX", "VY", "VZ", "WA", "WB", "WC", "WD", "WE", "WF", "WG", "WH", "WI", "WJ", "WK", "WL", "WM", "WN", "WO", "WP", "WQ", "WR", "WS", "WT", "WU", "WV", "WW", "WX", "WY", "WZ", "XA", "XB", "XC", "XD", "XE", "XF", "XG", "XH", "XI", "XJ", "XK", "XL", "XM", "XN", "XO", "XP", "XQ", "XR", "XS", "XT", "XU", "XV", "XW", "XX", "XY", "XZ", "YA", "YB", "YC", "YD", "YE", "YF", "YG", "YH", "YI", "YJ", "YK", "YL", "YM", "YN", "YO", "YP", "YQ", "YR", "YS", "YT", "YU", "YV", "YW", "YX", "YY", "YZ", "ZA", "ZB", "ZC", "ZD", "ZE", "ZF", "ZG", "ZH", "ZI", "ZJ", "ZK", "ZL", "ZM", "ZN", "ZO", "ZP", "ZQ", "ZR", "ZS", "ZT", "ZU", "ZV", "ZW", "ZX", "ZY", "ZZ" };

            int rowStartNumber = 3;

            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    worksheet.Cells[alphabet[i].ToString() + rowStartNumber].Value = dr[i].ToString();
                }
                rowStartNumber++;
            }

            using (var range = worksheet.Cells[2, 1, 2, columnCount])
            {
                // Setting bold font
                range.Style.Font.Bold = true;
                // Setting fill type solid
                range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                // Setting background color dark blue
                range.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);
                // Setting font color
                range.Style.Font.Color.SetColor(Color.White);
            }

            // Setting AutoFit for all cells
            worksheet.Cells.AutoFitColumns(0);

            // Lets set the header text
            worksheet.HeaderFooter.OddHeader.CenteredText = ReportName;

            // Add the page number to the right of the footer + total number of pages
            worksheet.HeaderFooter.OddFooter.RightAlignedText = string.Format("Page {0} of {1}", ExcelHeaderFooter.PageNumber, ExcelHeaderFooter.NumberOfPages);

            // Add the sheet name to center of the footer
            worksheet.HeaderFooter.OddFooter.CenteredText = ExcelHeaderFooter.SheetName;

            // Add the filepath to the left of the footer
            worksheet.HeaderFooter.OddFooter.LeftAlignedText = ExcelHeaderFooter.FileName;

            // At the time of printing, when page page breaks, then the header will come in the next page by enabling this settings...
            worksheet.PrinterSettings.RepeatRows = worksheet.Cells["1:1"];
            worksheet.PrinterSettings.RepeatColumns = worksheet.Cells["A:" + alphabet[columnCount - 1].ToString()];
            //worksheet.PrinterSettings.PrintArea = worksheet.Cells["A,I"];
            worksheet.PrinterSettings.PaperSize = ePaperSize.A4;
            worksheet.PrinterSettings.Orientation = eOrientation.Landscape;
            worksheet.PrinterSettings.Scale = 100;

            // Change the sheet view to show it in page layout mode
            worksheet.View.PageLayoutView = false;

            // Setting some document properties
            package.Workbook.Properties.Title = ReportName;
            package.Workbook.Properties.Author = "Omer Mollamehmetoglu";
            package.Workbook.Properties.Comments = "This document created by ACME Co.Ltd.";

            // set some extended property values
            package.Workbook.Properties.Company = "ACME Co.Ltd.";

            // set some custom property values
            package.Workbook.Properties.SetCustomPropertyValue("Checked by", "Omer Mollamehmetoglu");
            package.Workbook.Properties.SetCustomPropertyValue("AssemblyName", "ACME Co.Ltd.");
            // save our new workbook and we are done!

            package.Save();
        }

        return newFile.FullName;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM