Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从Excel中的特定行或列读取数据?_C#_Excel - Fatal编程技术网

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

C# 如何从Excel中的特定行或列读取数据?,c#,excel,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"); xlWork

这是我正在使用的代码,但它可以读取整个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);
     }
}
应用xlApp;
工作手册;
工作表;
射程;
字符串str;
int rCnt=0;
int-cCnt=0;
xlApp=新应用程序();
xlWorkBook=xlApp.Workbooks.Open(“c:\\tellets.xlsx”);
xlWorkSheet=(工作表)xlWorkBook.Worksheets.get_项(1);
range=xlWorkSheet.UsedRange;

对于RCNT=1;RCENT<P>用于简单地读取一个单元或一系列单元,如下面所示使用OLeDB数据提供程序。OLeDB不需要担心清理对象,如果程序意外地终止,Office自动化对象与OLeDB不同而留在内存中。下面我将介绍一种构建连接字符串ALS的体面方法。o、 请随意使用OneDrive

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();
        }
    }
}
使用系统;
使用系统数据;
使用System.Data.OleDb;
命名空间ExcelReadRangeSimple
{
内部课程计划
{
/// 
///此函数是一个示例,说明如何为
///基于扩展名的Excel文件。
/// 
/// 
/// 
/// 
/// 
///无法保证以下设置对于以下情况是正确的
///你的Excel文件。如果不起作用,需要调整的内容
///  
///-IMEX
///-HDR
///  
///另请参见IMEX
///  http://www.codeproject.com/Articles/37055/Working-with-MS-Excel-xls-xlsx-Using-MDAC-and-Oled
/// 
静态公共字符串连接字符串(字符串文件名、字符串头)
{
OleDbConnectionStringBuilder=新的OleDbConnectionStringBuilder();
if(System.IO.Path.GetExtension(FileName.ToUpper()=“.XLS”)
{
Builder.Provider=“Microsoft.Jet.OLEDB.4.0”;
Add(“扩展属性”,string.Format(“Excel8.0;IMEX=1;HDR={0};”,标头));
}
其他的
{
Builder.Provider=“Microsoft.ACE.OLEDB.12.0”;
Add(“扩展属性”,string.Format(“Excel12.0;IMEX=1;HDR={0};”,标头));
}
Builder.DataSource=文件名;
返回Builder.ConnectionString;
}
/// 
/// 
/// 
///要读取的完整路径和文件名
///要读取的工作表名称,不附加$
///单元格至起始范围,即A1
///单元至终端范围,即D30
静态私有void DemoReadData(字符串文件名、字符串SheetName、字符串StartCell、字符串EndCell)
{
System.Text.StringBuilder sb=新的System.Text.StringBuilder();
DataTable dt=新的DataTable();
使用(OleDbConnection cn=new-OleDbConnection{ConnectionString=ConnectionString(文件名,“No”)})
{
cn.Open();
string SelectStatement=string.Format(“选择F1作为公司,选择F2作为来自[{0}${1}:{2}]的联系人”,SheetName,StartCell,EndCell);
使用(OleDbCommand cmd=new-OleDbCommand{CommandText=SelectStatement,Connection=cn})
{
Console.WriteLine();
Console.WriteLine(“连接字符串为”);
Console.WriteLine(cn.ConnectionString);
Console.WriteLine();
Console.WriteLine();
OleDbDataReader dr=cmd.ExecuteReader();
如果(哈斯罗博士)
{
while(dr.Read())
{
WriteLine({0,-25}{1}),dr.GetString(1),dr.GetString(0));
}
}
其他的
{
Console.WriteLine(“无行!!!”);
}
}
}
}
私有静态void Main(字符串[]args)
{
字符串文件名=System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,“WS1.xlsx”);
DemoReadData(文件名为“Sheet4”、“C7”、“D16”);
Console.ReadLine();
}
}
}

现在,如果你真的想使用Office自动化,请考虑下面介绍的模型,它对如何使用和销毁对象进行细致的处理,以确保所有被使用的对象都被正确地清理了。很多时候开发人员不花时间做这件事,应该。

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;
}
public void OpenExcel(字符串文件名、字符串SheetName、字符串CellAddress、字符串CellValue)
{
List SheetNames=新列表();
bool procedure=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(文件名);
xlApp.Visible=false;
xlWorkSheets=xlWorkBook.Sheets;

对于(int x=1;x),只需简单搜索即可。@MustafaAKTAŞ该问题和答案与此处发布的问题无关。@Mufaka请解释一下,当两人试图做完全相同的事情时,他们之间是如何毫无关联的。