【问题标题】:Format all excel column to General before filling to datatable在填充到数据表之前将所有 excel 列格式化为常规
【发布时间】:2012-08-14 06:31:33
【问题描述】:

是否可以在填充数据集之前将 Excel 工作表的所有列更改为常规类型?我不能在我的应用程序中使用 Interop 或任何其他 3rd 方 dll。我正在使用 OleDbDataAdapter 将数据填充到数据集。

string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + fileName + "';Extended Properties= 'Excel 12.0;HDR=NO;TypeGuessRows=0;ImportMixedTypes=General'";
OleDbConnection con = new OleDbConnection(SourceConstr);
string query = "Select * from [Sheet1$A9:FG100]";
OleDbDataAdapter data = new OleDbDataAdapter(query, con);
data.Fill(ds);

【问题讨论】:

  • 我假设您的意思是您希望将每一列都读取为字符串 (varchar) 类型,对吧?
  • 是的,字符串或通用类型都可以。有什么想法吗?
  • 这是个好问题。另见stackoverflow.com/questions/2567673/…
  • 感谢 lc 的快速响应,但我之前尝试过 ExcelDataReader,但它不适用于我的情况。我的 excel 文件包含诸如“234567.234653457”之类的货币值,并且在填充到数据集后,除了 4 精度外,我都丢失了所有值。但是,如果我将 excel 中的所有列更改为 General 类型,则将返回完整精度。有什么补救措施吗?
  • @All,最后我使用互操作,似乎没有其他方法...... :(

标签: c# asp.net .net


【解决方案1】:

一种方法是获取所有列并更改它们

foreach (DataColumn c in DT.Columns)
{
    iColumnCount++;
    if(iRowCount == 0)
        Worksheet.Cells[1, iColumnCount] = c.ColumnName;
    else
        Worksheet.Cells[iRowCount, iColumnCount] = c.ColumnName;

    Worksheet.Columns.AutoFit(); //Correct the width of the columns
    //THIS IS WHERE I WANT TO COLOR THE HEADERS
}


    foreach (DataRow r in DT.Rows)
    {
        iRowCount++;
        iColumnCount = 0;
        foreach (DataColumn c in DT.Columns)
        {
            iColumnCount++;
            if(iRowCount == 1)
                Worksheet.Cells[iRowCount + 1, iColumnCount] = r[c.ColumnName].ToString();
            else
                Worksheet.Cells[iRowCount, iColumnCount] = r[c.ColumnName].ToString();

            Worksheet.Columns.AutoFit(); //Correct the width of the columns
        }
    }

改变颜色或蚂蚁属性

Worksheet.Range["A1","G1"].Interior.Color = Excel.XlRgbColor.rgbDarkBlue;

Worksheet.Range["A1","G1"].name or header = Excel.XlRgbColor.rgbWhite;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2011-12-05
    • 2021-03-01
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多