C# spire.xls应用实例

C# spire.xls 初使用datagridview→.xlsx

首先,添加引用
C# spire.xls应用实例_第1张图片

C# spire.xls应用实例_第2张图片
实现代码如下:

using Spire.Xls;
public class xlsP
        {
            public string sheetname { get; set; }
            public DataTable dt { get; set; }
        }
private void SetToExcel(List<xlsP> lt_xp)
        {
            string machineno = cbox_machineno.Text;
            if (Directory.Exists(Application.StartupPath + "\\EXCELSAVE"))
            {
                Directory.CreateDirectory(Application.StartupPath + "\\EXCELSAVE");
            }
            try
            {
                if (File.Exists(Application.StartupPath + "\\EXCELSAVE\\" + machineno + ".xlsx"))
                {
                    try
                    {
                        File.Delete(Application.StartupPath + "\\EXCELSAVE\\" + machineno + ".xlsx");
                    }
                    catch
                    { }

                }
                Workbook book = new Workbook();
                book.CreateEmptySheets(lt_xp.Count);
                book.SaveToFile(Application.StartupPath + "\\EXCELSAVE\\" + machineno + ".xlsx", ExcelVersion.Version2007);
                for (int i = 0; i < lt_xp.Count; i++)
                {
                    xlsP xp = lt_xp[i];
                    Worksheet sheet = book.Worksheets[i];
                    sheet.InsertDataTable(xp.dt, true, 1, 1);
                    sheet.Name = xp.sheetname;
                }
                book.SaveToFile(Application.StartupPath + "\\EXCELSAVE\\" + machineno + ".xlsx", ExcelVersion.Version2007);
                System.Diagnostics.Process.Start(Application.StartupPath + "\\EXCELSAVE");
            }
            catch
            {
                MessageBox.Show("表格佔用,先關掉該機台名EXCEL文件!");
            }
            
        }
public DataTable GetDgvToTable(DataGridView dgv)
        {
            DataTable dt = new DataTable();

            // 列强制转换
            for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc = new DataColumn(dgv.Columns[count].Name.ToString());
                dt.Columns.Add(dc);
            }

            // 循环行
            for (int count = 0; count < dgv.Rows.Count; count++)
            {
                DataRow dr = dt.NewRow();
                for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                {
                    dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

spire功能很强大,有需求慢慢挖掘

你可能感兴趣的:(spire,笔记,c#)