使用c#读取excel表数据

时间:2015-11-30 08:21:00

标签: c# excel

我有几个excel表的excel文件。我想读取给定Excel工作表的 excel表中的所有数据,并将这些数据复制到另一个excel表中。 一个excel表可能有几个表

我是通过VBA完成的。我想找到一个C#代码来实现它。 这是我使用的VBA代码。

Dim tableObject As ListObject
Dim oLastRow As ListRow
Dim srcRow As Range

Set sheet = ThisWorkbook.Worksheets("Sheet1")
For Each tableObject In sheet.ListObjects
Set srcRow = tableObject.DataBodyRange
Set oLastRow = Worksheets("Sheet2").ListObjects("table1").ListRows.Add
srcRow.Copy
oLastRow.Range.PasteSpecial xlPasteValues
Next

2 个答案:

答案 0 :(得分:1)

尝试遵循:

public static DataTable exceldata(string filePath)
    {     
        DataTable dtexcel = new DataTable();
           bool hasHeaders = false;
            string HDR = hasHeaders ? "Yes" : "No";
            string strConn;
            if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
            else
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
            //Looping Total Sheet of Xl File
            /*foreach (DataRow schemaRow in schemaTable.Rows)
            {
            }*/
            //Looping a first Sheet of Xl File
            DataRow schemaRow = schemaTable.Rows[0];
            string sheet = schemaRow["TABLE_NAME"].ToString();
            if (!sheet.EndsWith("_"))
            {
                string query = "SELECT  * FROM [" + sheet3 + "]";
                OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
                dtexcel.Locale = CultureInfo.CurrentCulture;
                daexcel.Fill(dtexcel);
            }

        conn.Close();
        return dtexcel;

    }

您还可以使用以下代码部分从Excel工作表中的表中导入数据

static void Main(string[] args)
{
try
{
    ReadInData readInData = new ReadInData(@"C:\SC.xlsx", "sc_2014");
    IEnumerable<Recipient> recipients = readInData.GetData();
}
catch (Exception ex)
{
    if(!(ex is FileNotFoundException || ex is ArgumentException || ex is FileToBeProcessedIsNotInTheCorrectFormatException))
        throw;
    Console.WriteLine(ex.Message);
}
Console.Write(Press any key to continue...);
Console.ReadKey(true);
}

public static class ReadInData
{
public static IEnumerable<Recipient> GetData(string path, string worksheetName, bool isFirstRowAsColumnNames = true)
{
    return new ExcelData(path).GetData(worksheetName, isFirstRowAsColumnNames)
        .Select(dataRow => new Recipient()
        {
            Municipality = dataRow["Municipality"].ToString(),
            Sexe = dataRow["Sexe"].ToString(),
            LivingArea = dataRow["LivingArea"].ToString()
        });
}
}

private static IExcelDataReader GetExcelDataReader(string path, bool isFirstRowAsColumnNames)
{
using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.Read))
{
    IExcelDataReader dataReader;

    if (path.EndsWith(".xls"))
        dataReader = ExcelReaderFactory.CreateBinaryReader(fileStream);
    else if (path.EndsWith(".xlsx"))
        dataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
    else
        throw new FileToBeProcessedIsNotInTheCorrectFormatException("The file to be processed is not an Excel file");

    dataReader.IsFirstRowAsColumnNames = isFirstRowAsColumnNames;
    return dataReader;
}
}

private static DataSet GetExcelDataAsDataSet(string path, bool isFirstRowAsColumnNames)
{
return GetExcelDataReader(path, isFirstRowAsColumnNames).AsDataSet();
}

private static DataTable GetExcelWorkSheet(string path, string workSheetName, bool isFirstRowAsColumnNames)
{
DataTable workSheet = GetExcelDataAsDataSet(path, isFirstRowAsColumnNames).Tables[workSheetName];
if (workSheet == null)
    throw new WorksheetDoesNotExistException(string.Format("The worksheet {0} does not exist, has an incorrect name, or does not have any data in the worksheet", workSheetName));
return workSheet;
    }

private static IEnumerable<DataRow> GetData(string path, string workSheetName, bool isFirstRowAsColumnNames = true)
{
return from DataRow row in GetExcelWorkSheet(path, workSheetName, isFirstRowAsColumnNames).Rows select row;
}

答案 1 :(得分:1)

我认为你会发现Excel的COM接口与VBA非常相似,因为类库都是相同的。唯一的挑战是抓取Excel实例然后管理语法差异(即VBA使用括号表示索引器,C#使用方括号)。

假设您的VBA正常工作,这应该是C#中相同的代码,以获取Excel的开放实例并完成您所做的工作。如果你想打开一个新的Excel实例,这实际上更容易(对谷歌来说非常容易):

Excel.Application excel;
Excel.Workbook wb;

try
{
    excel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
    excel.Visible = true;
    wb = (Excel.Workbook)excel.ActiveWorkbook;
}
catch (Exception ex)
{
    ErrorMessage = "Trouble Locating Open Excel Instance";
    return;
}

Excel.Worksheet sheet = wb.Worksheets["Sheet1"];

foreach (Excel.ListObject lo in sheet.ListObjects)
{
    Excel.Range srcRow = lo.DataBodyRange;
    Excel.ListRow oLastRow = wb.Worksheets["Sheet2"].ListObjects["table1"].ListRows.Add();
    srcRow.Copy();
    oLastRow.Range.PasteSpecial(Excel.XlPasteType.xlPasteValues);
}

这一切都预先假定您引用了Excel COM并设置了您的使用:

using Excel = Microsoft.Office.Interop.Excel;