zoukankan      html  css  js  c++  java
  • c#读写excel

    using System;
    using System.Data;
    using  Excel= Microsoft.Office.Interop.Excel;
    
    namespace 读写excel
    {
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow
        {
            public MainWindow()
            {
                InitializeComponent();
    
    
                // ReSharper disable once UnusedVariable
              //var x = GetData("d:\1.xlsx");
              //GC.Collect();
              //GC.WaitForPendingFinalizers();
              //GC.Collect();
            
             //   test("d:\1.xlsx");
    
                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn("sasfadf"));
                dt.Columns.Add(new DataColumn("sasfadf2"));
                dt.Columns.Add(new DataColumn("sasfadfss三代富贵"));
                for (int i = 0; i < 10; i++)
                {
                      DataRow dr = dt.NewRow();
                dr[0] = "1234";
                dr[2] = "萨芬";
                dr[1] = "asdfha";
                dt.Rows.Add(dr);
                }
              
               
                string errMsg;
           bool ok=     Set(dt, "d:\32.xlsx", out errMsg);
    
            }
    
    
            static DataTable GetData(string excelFilePath,bool hasTitle = false)
            { 
                var app = new Excel.Application();
                object oMissiong = System.Reflection.Missing.Value;
                Excel._Workbook workbook = null;
                var dt = new DataTable();
    
                try
                {
                    workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong,
                        oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
                    var sheets = workbook.Worksheets;
    
                    //将数据读入到DataTable中
                    var worksheet = (Excel.Worksheet)sheets.Item[1];//读取第一张表   
                    if (worksheet == null) return null;
    
                    var iRowCount = worksheet.UsedRange.Rows.Count;
                    var iColCount = worksheet.UsedRange.Columns.Count;
                    //生成列头
                    for (var i = 0; i < iColCount; i++)
                    {
                        var name = "column" + i;
                        if (hasTitle)
                        {
                            var txt = ((Excel.Range)worksheet.Cells[1, i + 1]).Text.ToString();
                            if (!string.IsNullOrWhiteSpace(txt)) name = txt;
                        }
                        while (dt.Columns.Contains(name)) name = name + "_1";//重复行名称会报错。
                        dt.Columns.Add(new DataColumn(name, typeof(string)));
                    }
                    //生成行数据
                    var rowIdx = hasTitle ? 2 : 1;
                    for (var iRow = rowIdx; iRow <= iRowCount; iRow++)
                    {
                        var dr = dt.NewRow();
                        for (var iCol = 1; iCol <= iColCount; iCol++)
                        {
                            var range = (Excel.Range)worksheet.Cells[iRow, iCol];
                            dr[iCol - 1] = (range.Value2 == null) ? "" : range.Text.ToString(); 
                        }
                        dt.Rows.Add(dr);
                    }
                    return dt;
                }
                catch { return null; }
                finally
                {
                    if (workbook != null)
                    {
                        workbook.Close(false, oMissiong, oMissiong);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);  
                    }
                    app.Workbooks.Close();
                    app.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);  
                }
            }
    
    
            private static bool Set(DataTable dt, string excelFilePath, out string errMsg )
            {
                Microsoft.Office.Interop.Excel.Application app = null;
                Microsoft.Office.Interop.Excel._Workbook workbook = null; 
                object oMissiong = System.Reflection.Missing.Value;
                try
                {
                    app = new Microsoft.Office.Interop.Excel.Application();
                    app.DisplayAlerts = false; 
                    workbook = app.Workbooks.Add(true);
                   
                    //将数据读入到DataTable中
                    var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Item[1]; //读取第一张表   
                    if (worksheet == null) {   errMsg = "asdg";
                        return false; }
                     
    
                    var iRowCount = dt.Rows.Count;
                    var iColCount =dt.Columns.Count;
                    //生成列头
                    for (var i = 0; i < iColCount; i++)
                    {
                        worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName; 
                    }  
                    for (var iRow = 2; iRow <= iRowCount; iRow++)
                    { 
                        for (var iCol = 1; iCol <= iColCount; iCol++)
                        {
                          worksheet.Cells[iRow, iCol]=dt.Rows[iRow-2][iCol-1].ToString(); 
                        } 
                    }
                    errMsg = "";
                    return true;
                }
                catch (Exception ex)
                {
                    errMsg = ex.Message;
                    return false;
                }
                finally
                {
                    if (workbook != null)
                    {
                        workbook.Close(true, excelFilePath, oMissiong);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                    }
                    if (app != null)
                    {
                        app.Workbooks.Close();
                        app.Quit();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                    }
                }
            }
            //void test(string sourceFile)
            //{
            //    var app = new Microsoft.Office.Interop.Excel.Application();
            //    var tp = app.GetType();
            //    var workBook = app.Workbooks;
            //    var elType = workBook.GetType();
            //    object objelName = sourceFile;
            //    var ebook = (Microsoft.Office.Interop.Excel.Workbook)elType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, workBook, new Object[] { objelName, true, true });
            //    Object missing = System.Reflection.Missing.Value;
            //    for (var i = 0; i < ebook.Worksheets.Count; i++)
            //    {
            //        Excel.Worksheet ws = ebook.Worksheets[i + 1];
            //        ws.PageSetup.Orientation = Excel.XlPageOrientation.xlPortrait;//页面方向竖向
            //        ws.PageSetup.Zoom = false;
            //        ws.PageSetup.FitToPagesWide = 1;
            //        ws.PageSetup.FitToPagesTall = false;
            //    }
            //    ebook.PrintOut(missing, missing, missing, missing, missing, true, missing, "d:\2.xps");
            //    tp.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, app, null);
            //   // workBook.Close();
            //  //  app.Quit();
    
            //}
    
        }
    }
  • 相关阅读:
    NHibernate OR EES ,不能比较的比较
    Dubbo实现原理和实现机制
    xxljob学习1:整体架构
    xxljob学习2:用户端注册
    xxljob学习4:任务调度器
    xxljob学习3:服务端一次调度
    jQuery源码学习(1)——addClass
    jQuery 选择器项目实例
    javascript权威指南读书笔记(1)——对象
    easyui tabs源码阅读(未完待续)
  • 原文地址:https://www.cnblogs.com/congqiandehoulai/p/12733046.html
Copyright © 2011-2022 走看看