如何将单元格值导入数组以插入数据库或对象?

时间:2017-06-20 19:32:48

标签: c# excel

我正在研究如何将excel文件中的信息导入到DB中的不同表中,问题是我已经实现了以下代码,但在执行时我无法看到我是否正确读取了单元格中的信息,现在阅读完之后我想开始对我感兴趣的信息进行分类,然后选择我应该在对象或数据库中插入哪些信息

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web;
using System.Text;
using Microsoft.CSharp;
using Microsoft.Office.Interop.Excel; 
using System.Linq;
using System.Runtime.InteropServices;

namespace WebApplication2
{
   public class ImportExcel
   {


    public void GetValuesExcel()
    {

        Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(@"C:\Users\JULIO.xlsx");
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet = xlWorkBook.Sheets[1];
        Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;


        int rowCount = xlRange.Rows.Count;
        int colCount = xlRange.Columns.Count;


        for (int i = 1; i <= rowCount; i++)
        {
            for (int j = 1; j <= colCount; j++)
            {
                //new line
                if (j == 1)
                    Console.Write("\r\n");

                //write the value to the console
                if (xlRange.Cells[i, j] != null)
                    Console.Write(xlRange.Cells[i, j].ToString() + "\t");
            }
        }

        //cleanup
        GC.Collect();
        GC.WaitForPendingFinalizers();

        //rule of thumb for releasing com objects:
        //  never use two dots, all COM objects must be referenced and released individually
        //  ex: [somthing].[something].[something] is bad

        //release com objects to fully kill excel process from running in the background
        Marshal.ReleaseComObject(xlRange);
        Marshal.ReleaseComObject(xlWorkSheet);

        //close and release
        xlWorkBook.Close();
        Marshal.ReleaseComObject(xlWorkBook);

        //quit and release
        xlApp.Quit();
        Marshal.ReleaseComObject(xlApp);
    }

    public void Main(string[] args)
    {
        GetValuesExcel();

    }
   }
 }

excel表包含以下行:

  1. 数字
  2. 用户名
  3. 创作
  4. 日期
  5. 费用
  6. 出发日期
  7. 抵达日期

0 个答案:

没有答案