c# - 在填充到数据表之前将所有 excel 列格式化为常规

标签 c# asp.net .net

是否可以在填充到数据集之前将 Excel 工作表的所有列更改为通用类型?我不能在我的应用程序中使用 Interop 或任何其他第 3 方 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);

最佳答案

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

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
        }
    }

改变颜色或 Ant 属性

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

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

关于c# - 在填充到数据表之前将所有 excel 列格式化为常规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11946906/

相关文章:

c# - 使用 Entity Framework 6 在数据库中查找等效的嵌套对象

C#:如何以编程方式将 SQL 脚本导入数据库?

asp.net - 不同主机上的表单例份验证

具有可选 URL 段的 ASP.NET 路由

c# - 同一解决方案中两个不同项目的相同 Nuget 包

c# - 如何使用 DES 实现 CBC-MAC?

c# - 使用 EnterpriseLibrary.TransientFaultHandling 的 SQL Azure 重试逻辑

c# - 通过ASP.Net网站下载文件

c# - 如何在不使用 .NET 中的 WMI 的情况下找到硬盘设备序列号?

c# - 如何在保存 native 内存的类上实现 AsSpan()?