任何人都可以帮助动态格式化两列的货币数据类型吗?
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using System.Reflection;
namespace ST_367d705c54de4e9e9f890350f933c80b.csproj
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
public void Main()
{
string basePath = Dts.Variables["User::VarDirectoryPath"].Value.ToString();
try
{
OleDbDataAdapter A = new OleDbDataAdapter();
System.Data.DataTable dt = new System.Data.DataTable();
var delimiter = Dts.Variables["User::VarDelimiter"].Value.ToString();
A.Fill(dt, Dts.Variables["User::VarObject"].Value);
basePath = Dts.Variables["User::VarDirectoryPath"].Value.ToString();
string filePath = Path.Combine(basePath, (Dts.Variables["User::VarFileName_1"].Value.ToString()
+ Dts.Variables["User::VarDate"].Value.ToString() + Dts.Variables["User::VarFileExtension_1"].Value.ToString()));
int i = 0;
StreamWriter sw = null;
using (sw = new StreamWriter(filePath, false))
{
for (i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dt.Columns[i].ToString() + Dts.Variables["User::VarDelimiter"].Value.ToString());
}
sw.WriteLine();
foreach (DataRow row in dt.Rows)
{
object[] array = row.ItemArray;
for (i = 0; i < array.Length; i++)
{
object val = array[i];
if (val == "0")
sw.Write(string.Format("#.##", val) + delimiter);
else
sw.Write(val + delimiter);
}
sw.WriteLine();
}
sw.Close();
}
}
catch (Exception ex)
{
string file = string.Format("err_{0}.txt", Dts.Variables["User::VarDate"].Value.ToString());
File.WriteAllText(Path.Combine(basePath, file), ex.ToString());
}
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
有什么建议吗?数据表中有10列,而第3,4,5列需要格式化为两位小数,如果值等于零或为空,还需要输入0.00。
答案 0 :(得分:0)
以下是格式化小数的示例:
https://dotnetfiddle.net/da7UoR
using System;
public class Program
{
public static void Main()
{
decimal val1 = 0m;
decimal val2 = 125580m;
Console.WriteLine(val1.ToString("0.00"));
//Output 0.00
Console.WriteLine(val2.ToString("0.00"));
//Output 125580.00
//Money format
Console.WriteLine(val1.ToString("C"));
//Output $0.00
Console.WriteLine(decimalToFormattedString(val1));
//Output 0.00
Console.WriteLine(decimalToFormattedString(val2));
//Output 125580.00
}
public static string decimalToFormattedString(decimal myValue)
{
return myValue.ToString("0.00");
}
}