gpt4 book ai didi

c# - 比较数据集中的单元格和前置信息

转载 作者:行者123 更新时间:2023-11-30 19:39:24 27 4
gpt4 key购买 nike

好吧,我对我的 C# 有点生疏,所以这可能很容易,但我只是没有得到,但它晚了,我的大脑受伤了。我正在尝试获取数据集中的每个值,如果它们短于给定长度,则在开头添加零。问题是我不知道如何着手实现它的概念。任何帮助表示赞赏。这是我到目前为止所拥有的。

        //Connection and location to Excel file
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\\Users\\User\\Desktop\\New folder\\DHS_Weekly.xlsx; Extended Properties= \"Excel 12.0;HDR=No;IMEX=1;ImportMixedTypes=Text;\"";

//Select location in the file
OleDbCommand command = new OleDbCommand
(
"SELECT * FROM [WEEKLY.COOLING.PAYMENT$C:D]", conn
);
//Create a dataset to temp store the information
DataSet dsDHS = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(dsDHS);


//Having the data Grid display the results of the data set DHS(dsDHS)
dataGridView1.DataSource = dsDHS.Tables[0];

//New string that sets the path to the output of a text file
//The dataset will be output to this text file
string path = @"C:\\Users\\User\\Desktop\\New folder\\DHStest.txt";

//New streamwriter and stringbuilder that uses the path created above
StreamWriter textOut = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write));
StringBuilder str = new StringBuilder();

//uses strings to correctly display the dataset
//removes the last 3 rows from output (2 Null rows and last line not needed)
//removes the first row by starting at 1 instead of zero. (first row is null)
for (int i = 1; i <= dsDHS.Tables[0].Rows.Count - 3; i++)
{
for (int j = 0; j <= dsDHS.Tables[0].Columns.Count - 1; j++)
{
str.Append(dsDHS.Tables[0].Rows[i][j].ToString());
}
//Adds a new line between each row
str.AppendLine();
}
//writes the output, this is just so I can check things before finalizing
textOut.Write(str.ToString());
textOut.Close();

}
}

最佳答案

假设我正确理解您的要求,并且您希望最终长度为 6 个字符:

for (int j = 0; j <= dsDHS.Tables[0].Columns.Count - 1; j++)
{
var originalValue = dsDHS.Tables[0].Rows[i][j].ToString();
var padded = originalValue.PadLeft(6, '0');

str.Append(padded);
}

将“6”更改为所需的最终宽度。

关于c# - 比较数据集中的单元格和前置信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27773077/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com