在工作表中选择范围C#

时间:2013-05-10 16:29:31

标签: c# ole

我目前在excel电子表格中打开并阅读以下代码:

var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;", fileNameTextBox.Text);
var queryString = String.Format("SELECT * FROM [{0}]",DETAILS_SHEET_NAME);
var adapter = new OleDbDataAdapter(queryString, connectionString);
var ds = new DataSet();

adapter.Fill(ds, DETAILS_SHEET_NAME);

DataTable data = ds.Tables[DETAILS_SHEET_NAME];

dataGridView1.DataSource = data;
                dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);

这一切都很好,除了我对工作表的第一行(可能是前两行,因为第2行是标题)不感兴趣。如何修改选择查询以选择像我在excel中那样的范围?

我有兴趣阅读列A-N的行,从2开始包含数据的所有行。

我还需要在不同的工作表上访问几个特定的​​单元格,我假设我必须为每个单元格构建另一个具有不同查询字符串的适配器?

2 个答案:

答案 0 :(得分:2)

修改Select语句,包括您需要的列而不是通配符"*",如下例所示:

("SELECT Column1, Column2 FROM DETAILS_SHEET_NAME");

您可以应用其他逻辑以删除不必要的行,例如,“寻呼解决方案”(即从N到M中选择行),如下所示:

假设数据库表“TBL_ITEM”包含两个感兴趣的列(字段):“Item”列,表示唯一ID和“Rank”,用于按升序排序,一般的分页问题如下所述:从按Rank offset(即跳过)(MN)行排序的表中选择N行:

SELECT TOP N Item, 
Rank FROM (SELECT TOP M Rank, Item FROM TBL_ITEM ORDER BY Rank) 
AS [SUB_TAB] ORDER BY Rank DESC 

我的文章 Pure SQL解决方案数据库表分页(链接:http://www.codeproject.com/Tips/441079/Pure-SQL-solution-to-Database-Table-Paging

详细讨论了此解决方案及其扩展/示例

最后,您可以使用清单2中所示的代码片段在Excel文件中导出DataTable对象的内容,其中包含大量可以添加到代码中的自定义功能;

清单2.将DataTable导出到Excel文件(2007/2010):

internal static bool Export2Excel(DataTable dataTable, bool Interactive) 
{
    object misValue = System.Reflection.Missing.Value;

    // Note: don't include Microsoft.Office.Interop.Excel in reference (using),
    // it will cause ambiguity w/System.Data: both have DataTable obj
    Microsoft.Office.Interop.Excel.Application _appExcel = null;
    Microsoft.Office.Interop.Excel.Workbook _excelWorkbook = null;
    Microsoft.Office.Interop.Excel.Worksheet _excelWorksheet = null;
    try
    {
        // excel app object
        _appExcel = new Microsoft.Office.Interop.Excel.Application();

        // make it visible to User if Interactive flag is set
        _appExcel.Visible = Interactive;

        // excel workbook object added to app
        _excelWorkbook = _appExcel.Workbooks.Add(misValue);

        _excelWorksheet = _appExcel.ActiveWorkbook.ActiveSheet 
            as Microsoft.Office.Interop.Excel.Worksheet;

        // column names row (range obj)
        Microsoft.Office.Interop.Excel.Range _columnsNameRange;
        _columnsNameRange = _excelWorksheet.get_Range("A1", misValue);
        _columnsNameRange = _columnsNameRange.get_Resize(1, dataTable.Columns.Count);

        // data range obj
        Microsoft.Office.Interop.Excel.Range _dataRange;
        _dataRange = _excelWorksheet.get_Range("A2", misValue);
        _dataRange = _dataRange.get_Resize(dataTable.Rows.Count, dataTable.Columns.Count);

        // column names array to be assigned to columnNameRange
        string[] _arrColumnNames = new string[dataTable.Columns.Count];

        // 2d-array of data to be assigned to _dataRange
        string[,] _arrData = new string[dataTable.Rows.Count, dataTable.Columns.Count];

        // populate both arrays: _arrColumnNames and _arrData
        // note: 2d-array structured as row[idx=0], col[idx=1]
        for (int i = 0; i < dataTable.Columns.Count; i++)
        {
            for (int j = 0; j < dataTable.Rows.Count; j++)
            {
                _arrColumnNames[i] = dataTable.Columns[i].ColumnName;
                _arrData[j, i] = dataTable.Rows[j][i].ToString();
            }
        }

        //assign column names array to _columnsNameRange obj
        _columnsNameRange.set_Value(misValue, _arrColumnNames);

        //assign data array to _dataRange obj
        _dataRange.set_Value(misValue, _arrData);

        // save and close if Interactive flag not set
        if (!Interactive)
        {
            // Excel 2010 - "14.0"
            // Excel 2007 - "12.0"
            string _ver = _appExcel.Version;

            string _fileName ="TableExport_" + 
                DateTime.Today.ToString("yyyy_MM_dd") + "-" +
                DateTime.Now.ToString("hh_mm_ss");

            // check version and select file extension
            if (_ver == "14.0" || _ver == "12.0")  { _fileName += ".xlsx";}
            else { _fileName += ".xls"; }

            // save and close Excel workbook
            _excelWorkbook.Close(true, "{DRIVE LETTER}:\\" + _fileName, misValue);
        }
        return true;
    }
    catch (Exception ex) {  throw; }
    finally
    {
        // quit excel app process
        if (_appExcel != null)
        {
            _appExcel.UserControl = false;
            _appExcel.Quit();
            _appExcel = null;
            misValue = null;
        }
    }
}

答案 1 :(得分:0)

你可以简单地要求没有标题。修改您的连接字符串,添加HDR=No

对于您的第二个问题,我发现了post,也许您会发现它有用。