我们如何从Excel中的特定行或列读取数据?

时间:2016-01-06 09:47:23

标签: c# excel

这是我正在使用的代码,但它会读取整个Excel工作表。如何只从一个特定的列或行读取数据?

Application xlApp;
Workbook xlWorkBook;
Worksheet xlWorkSheet;
Range range;

string str;
int rCnt = 0;
int cCnt = 0;

xlApp = new Application();
xlWorkBook = xlApp.Workbooks.Open("c:\\telltales.xlsx");
xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);

range = xlWorkSheet.UsedRange;

for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
     for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
     {
          str = (string)(range.Cells[rCnt, cCnt] as Range).Value2;
          Console.WriteLine(str);
     }
}

1 个答案:

答案 0 :(得分:1)

如果只是读取一个细胞或一系列细胞,请考虑使用OleDb数据提供者,如下所示。使用OleDb时,无需担心清理对象,如果程序意外终止,办公自动化对象会留在内存中,而不像OleDb。下面我还提供了构建连接字符串的正确方法。从OneDrive免费download the project

using System;
using System.Data;
using System.Data.OleDb;

namespace ExcelReadRangeSimple
{
    internal class Program
    {
        /// <summary>
        /// This functiuon is an example of how you can setup a connection for an
        /// Excel file based on the extension.
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="Header"></param>
        /// <returns></returns>
        /// <remarks>
        ///  There are no guaranty that the settings below will be correct for
        ///  your Excel file. Things to tweak if it does not work
        ///  
        ///  - IMEX
        ///  - HDR
        ///  
        ///  SeeAlso for IMEX
        ///  http://www.codeproject.com/Articles/37055/Working-with-MS-Excel-xls-xlsx-Using-MDAC-and-Oled
        /// </remarks>
        static public string ConnectionString(string FileName, string Header)
        {
            OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder();
            if (System.IO.Path.GetExtension(FileName).ToUpper() == ".XLS")
            {
                Builder.Provider = "Microsoft.Jet.OLEDB.4.0";
                Builder.Add("Extended Properties", string.Format("Excel 8.0;IMEX=1;HDR={0};", Header));
            }
            else
            {
                Builder.Provider = "Microsoft.ACE.OLEDB.12.0";
                Builder.Add("Extended Properties", string.Format("Excel 12.0;IMEX=1;HDR={0};", Header));
            }

            Builder.DataSource = FileName;

            return Builder.ConnectionString;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="FileName">Full path and file name to read</param>
        /// <param name="SheetName">Name of sheet to read, do not append $</param>
        /// <param name="StartCell">Cell to start range i.e. A1</param>
        /// <param name="EndCell">Cell to end range i.e. D30</param>
        static private void DemoReadData(string FileName, string SheetName, string StartCell, string EndCell)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            DataTable dt = new DataTable();

            using (OleDbConnection cn = new OleDbConnection { ConnectionString = ConnectionString(FileName, "No") })
            {
                cn.Open();

                string SelectStatement = string.Format("SELECT F1 As Company, F2 As Contact FROM [{0}${1}:{2}]", SheetName, StartCell, EndCell);

                using (OleDbCommand cmd = new OleDbCommand { CommandText = SelectStatement, Connection = cn })
                {

                    Console.WriteLine();
                    Console.WriteLine("Connection string is");
                    Console.WriteLine(cn.ConnectionString);
                    Console.WriteLine();
                    Console.WriteLine();

                    OleDbDataReader dr = cmd.ExecuteReader();
                    if (dr.HasRows)
                    {
                        while (dr.Read())
                        {
                            Console.WriteLine("   {0,-25} {1}", dr.GetString(1), dr.GetString(0));
                        }
                    }
                    else
                    {
                        Console.WriteLine("No rows!!!");
                    }
                }
            }



        }
        private static void Main(string[] args)
        {
            string FileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WS1.xlsx");

            DemoReadData(FileName, "Sheet4", "C7", "D16");
            Console.ReadLine();
        }
    }
}

现在,如果您真的想要使用办公自动化,请考虑遵循下面介绍的模型,该模型对于如何使用和销毁对象非常细致,以确保正确清理所有使用的对象。很多时候,开发人员不会花时间去做这件事,应该这样做。

public void OpenExcel(string FileName, string SheetName, string CellAddress, string CellValue)
{
    List<string> SheetNames = new List<string>();

    bool Proceed = false;
    Excel.Application xlApp = null;
    Excel.Workbooks xlWorkBooks = null;
    Excel.Workbook xlWorkBook = null;
    Excel.Worksheet xlWorkSheet = null;
    Excel.Sheets xlWorkSheets = null;

    xlApp = new Excel.Application();
    xlApp.DisplayAlerts = false;
    xlWorkBooks = xlApp.Workbooks;
    xlWorkBook = xlWorkBooks.Open(FileName);

    xlApp.Visible = false;
    xlWorkSheets = xlWorkBook.Sheets;

    for (int x = 1; x <= xlWorkSheets.Count; x++)
    {
        xlWorkSheet = (Excel.Worksheet)xlWorkSheets[x];

        SheetNames.Add(xlWorkSheet.Name);

        if (xlWorkSheet.Name == SheetName)
        {
            Proceed = true;
            Excel.Range xlRange1 = null;
            xlRange1 = xlWorkSheet.Range[CellAddress];
            xlRange1.Value = CellValue;

            string value = xlRange1.Value;
            Console.WriteLine(value);

            Marshal.FinalReleaseComObject(xlRange1);
            xlRange1 = null;
            xlWorkSheet.SaveAs(FileName);
            break;
        }

        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet);
        xlWorkSheet = null;
    }

    xlWorkBook.Close();
    xlApp.Quit();

    ReleaseComObject(xlWorkSheets);
    ReleaseComObject(xlWorkSheet);
    ReleaseComObject(xlWorkBook);
    ReleaseComObject(xlWorkBooks);
    ReleaseComObject(xlApp);

    if (Proceed)
    {
        MessageBox.Show("Found sheet, do your work here.");
    }
    else
    {
        MessageBox.Show("Sheet not located");
    }

    MessageBox.Show("Sheets available \n" + String.Join("\n", SheetNames.ToArray()));
}

private void ReleaseComObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception)
    {
        obj = null;
    }
}

public string GetCellValue(string FileName, string SheetName, string CellAddress)
{
    string CellValue = "";

    Excel.Application xlApp = null;
    Excel.Workbooks xlWorkBooks = null;
    Excel.Workbook xlWorkBook = null;
    Excel.Worksheet xlWorkSheet = null;
    Excel.Sheets xlWorkSheets = null;

    xlApp = new Excel.Application();
    xlApp.DisplayAlerts = false;
    xlWorkBooks = xlApp.Workbooks;
    xlWorkBook = xlWorkBooks.Open(FileName);

    xlApp.Visible = false;
    xlWorkSheets = xlWorkBook.Sheets;

    for (int x = 1; x <= xlWorkSheets.Count; x++)
    {
        xlWorkSheet = (Excel.Worksheet)xlWorkSheets[x];

        if (xlWorkSheet.Name == SheetName)
        {
            Excel.Range xlRange1 = null;
            xlRange1 = xlWorkSheet.Range[CellAddress];
            CellValue = xlRange1.Value;
            Marshal.FinalReleaseComObject(xlRange1);
            xlRange1 = null;
            xlWorkSheet.SaveAs(FileName);
            break;
        }

        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet);
        xlWorkSheet = null;
    }

    xlWorkBook.Close();
    xlApp.Quit();

    ReleaseComObject(xlWorkSheets);
    ReleaseComObject(xlWorkSheet);
    ReleaseComObject(xlWorkBook);
    ReleaseComObject(xlWorkBooks);
    ReleaseComObject(xlApp);
    return CellValue;
}
相关问题