c# excel转换为DataTable

 System.Data.DataTable GetDataFromExcelByCom(bool hasTitle, string fileName)
        {
            //OpenFileDialog openFile = new OpenFileDialog();
            //openFile.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
            //openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //openFile.Multiselect = false;
            //if (openFile.ShowDialog() == DialogResult.Cancel) return null;
            //var excelFilePath = openFile.FileName;

            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Sheets sheets;
            object oMissiong = System.Reflection.Missing.Value;
            Workbook workbook = null;
            System.Data.DataTable dt = new System.Data.DataTable();

            try
            {
                if (app == null) return null;
                workbook = app.Workbooks.Open(fileName, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong,
                    oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
                sheets = workbook.Worksheets;

                //将数据读入到DataTable中
                Worksheet worksheet = (Worksheet)sheets.get_Item(1);//读取第一张表
                if (worksheet == null) return null;

                int iRowCount = worksheet.UsedRange.Rows.Count;
                int iColCount = worksheet.UsedRange.Columns.Count;
                //生成列头
                for (int i = 0; i < iColCount; i++)
                {
                    var name = "column" + i;
                    if (hasTitle)
                    {
                        var txt = ((Range)worksheet.Cells[1, i + 1]).Text.ToString();
                        if (!string.IsNullOrEmpty(txt)) name = txt;
                    }
                    while (dt.Columns.Contains(name)) name = name + "_1";//重复行名称会报错。
                    dt.Columns.Add(new DataColumn(name, typeof(string)));
                }
                //生成行数据
                Range range;
                int rowIdx = hasTitle ? 2 : 1;
                for (int iRow = rowIdx; iRow <= iRowCount; iRow++)
                {
                    DataRow dr = dt.NewRow();
                    for (int iCol = 1; iCol <= iColCount; iCol++)
                    {
                        range = (Range)worksheet.Cells[iRow, iCol];
                        dr[iCol - 1] = (range.Value2 == null) ? "" : range.Text.ToString();
                    }
                    dt.Rows.Add(dr);
                }

                return dt;
            }
            catch { return null; }
            finally
            {
                workbook.Close(false, oMissiong, oMissiong);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                workbook = null;
                app.Workbooks.Close();
                app.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                app = null;
            }
        }

  

时间: 2024-10-27 04:52:03

c# excel转换为DataTable的相关文章

【c#操作office】--OleDbDataAdapter 与OleDbDataReader方式读取excel,并转换为datatable

OleDbDataAdapter方式: /// <summary> /// 读取excel的表格放到DataTable中 ---OleDbDataAdapter /// </summary> /// <param name="strSql"></param>        /// <param name="excelpath">excel路径</param> /// <returns>

将List中部分字段转换为DataTable中

由于原来方法导出数据量比较大 的时候,出现卡顿现象:搜索简单改造:(下面方法借助NPIO) /// <summary> /// 将List中原文和译文转换为Datatable /// </summary> /// <typeparam name="MemoryFields">术语</typeparam> /// <param name="list">术语列宁表</param> /// <r

C#实现将json转换为DataTable的方法

本文实例讲述了C#实现将json转换为DataTable的方法.分享给大家供大家参考.具体实现方法如下: 代码如下: #region 将json转换为DataTable /// <summary> /// 将json转换为DataTable /// </summary> /// <param name="strJson">得到的json</param> /// <returns></returns> private

将DataTable转换为List,将List转换为DataTable的实现类

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Xmh.DBUnit { /// <summary> /// 将DataTable转换为List,将

实体类转换为DataTable

下面为实体类转换为DataTable的一个小例子: 用到了反射知识. using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Net_ConsoleApplication { class Program { stat

List&lt;T&gt;转换为DataTable

public static class DataTableExtensions    {        /// <summary>        /// 转化一个DataTable        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="list"></param>    

c#常用的Datable转换为json,以及json转换为DataTable操作方法

#region  DataTable 转换为Json字符串实例方法/// <summary>/// GetClassTypeJosn 的摘要说明/// </summary>public class GetClassTypeJosn : IHttpHandler{    /// <summary>    /// 文件名:DataTable 和Json 字符串互转    /// 版权所有:Copyright (C) Create Family Wealth liangjw 

Excel.Application SaveAs 把excel转换为html

Excel.Application SaveAs 中的第二个参数的值: 可以直接用 10 进制的值代替左边的这些 xl 类型 . 例如:把excel转换为html的js: var oWB = oXL.Workbooks.open("d:\test.xls"); oWB.worksheets(i).select(); var oSheet = oWB.ActiveSheet; oSheet.SaveAs("d:\test.html",44); fileformat 类

C#将LINQ数据集转换为Datatable

1.方法一:(测试可用) //通过一个公共类将LINQ数据集转换为datatable public DataTable LINQToDataTable<T>(IEnumerable<T> varlist) {     DataTable dtReturn = new DataTable();     // column names      PropertyInfo[] oProps = null; if (varlist == null) return dtReturn; for