• Excel相关操作


    public static bool DataSetToExcel(DataSet dataSet, string filePath, bool isShowExcle = true)
            {
                DataTable dataTable = dataSet.Tables[0];
                int rowNumber = dataTable.Rows.Count;
                int columnNumber = dataTable.Columns.Count;
                if (rowNumber == 0)
                {
                    return false;
                }
    
                //建立Excel对象 
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel.Workbook workBook = excel.Application.Workbooks.Add(true);
                excel.Visible = false;//是否打开该Excel文件 
                excel.Cells.ColumnWidth = 16;//设置单元格宽
                excel.Cells.NumberFormatLocal = "@";//设置所有单元格式
                //生成字段名称 //从第一行开始 EXCEL起始索引为1
                for (int col = 0; col < columnNumber; col++)
                {
                    excel.Cells[1, col + 1] = dataTable.Columns[col].ColumnName;
                }
                //填充数据 //从第二行开始 
                for (int row = 0; row < rowNumber; row++)
                {
                    for (int col = 0; col < columnNumber; col++)
                    {
                        excel.Cells[row + 2, col + 1] = dataTable.Rows[row].ItemArray[col];
                        //if (col < 3)
                        //{
                        //    excel.Cells[row + 2, col + 1].NumberFormatLocal = "@";
                        //}
                    }
                }
                workBook.SaveAs(filePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                try
                {
                    workBook.Saved = true;
                    excel.UserControl = false;
                }
                catch (Exception ex)
                {
                    Log.Writer(ex, "DataSetToExcel异常");
                    return false;
                }
                finally
                {
                    workBook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, Missing.Value, Missing.Value);
                    excel.Quit();
                }
    
                if (isShowExcle)
                {
                    System.Diagnostics.Process.Start(filePath);
                }
                return true;
            }
    View Code
  • 相关阅读:
    AcWing 171. 送礼物
    AcWing 167. 木棒
    AcWing 166. 数独
    AcWing 168. 生日蛋糕
    AcWing 180 排书
    A*与IDA* 算法介绍
    AcWing 170. 加成序列[曾用名:加法链]
    AcWing 普通队列与循环队列写法
    AcWing 181. 回转游戏
    AcWing 1129. 热浪【单源最短路】
  • 原文地址:https://www.cnblogs.com/lee2011/p/6053467.html
Copyright © 2020-2023  润新知