C# 如何自定义从控制台应用程序导出的Excel?

C# 如何自定义从控制台应用程序导出的Excel?,c#,console-application,export-to-excel,C#,Console Application,Export To Excel,如何添加自定义列标题? 下面是我在控制台应用程序中使用的代码。 它工作正常 public static void Main(string[] args) { string path = Environment.CurrentDirectory + @"\ExportFrmInventoryInvsupplierSupplier.xls"; if (!File.Exists(path)) { // Creat

如何添加自定义列标题?

下面是我在控制台应用程序中使用的代码。 它工作正常

   public static void Main(string[] args)
    {


        string path = Environment.CurrentDirectory + @"\ExportFrmInventoryInvsupplierSupplier.xls";
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                //creating the file contents
            }
        }
        using (StreamWriter sw = File.CreateText(path))
        {
            SqlConnection cn = new SqlConnection("Data Source=DELL\\SQLSERVER1;Initial Catalog=Camo;Integrated Security=True;Trusted_Connection=True");
            //SqlConnection cn = new SqlConnection("Data Source=DELL\\SQLSERVER1;AttachDbFilename=|DataDirectory|\\Camo.mdf;Integrated Security=True;User Instance=True");
            SqlCommand cmd = new SqlCommand("SELECT distinct Inventory.LocalSKU, Inventory.ItemName, Inventory.Price, Inventory.Price2,InventorySuppliers.Cost,Suppliers.SupplierName,InventorySuppliers.SupplierSKU FROM Inventory Inner JOIN InventorySuppliers ON InventorySuppliers.LocalSKU =Inventory.LocalSKU Inner JOIN Suppliers ON  InventorySuppliers.SupplierID=Suppliers.SupplierID where InventorySuppliers.PrimarySupplier='True' order by Inventory.LocalSKU", cn);
            try
            {
                cn.Open();
                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    sw.WriteLine(dr["LocalSKU"].ToString() + "\t" + dr["ItemName"].ToString() + "\t" + dr["Price"].ToString() + "\t" + dr["Price2"].ToString() + "\t" + dr["Cost"].ToString() + "\t" + dr["SupplierName"].ToString() + "\t" + dr["SupplierSKU"].ToString());
                }

                Console.WriteLine("Exported Successfully...!!!");
            }
            catch (Exception excpt)
            {
                Console.WriteLine(excpt.Message);
            }

        }


    }

如果您只需要文件第一行中的列名,请尝试以下方法

SqlDataReader dr = cmd.ExecuteReader();
sw.WriteLine("LocalSKU\tItemName\tPrice\tPrice2\tCost\tSupplierName\tSupplierSKU");
while (dr.Read())
{
    sw.WriteLine(dr["LocalSKU"].ToString() + "\t" + dr["ItemName"].ToString() + "\t" + dr["Price"].ToString() + "\t" + dr["Price2"].ToString() + "\t" + dr["Cost"].ToString() + "\t" + dr["SupplierName"].ToString() + "\t" + dr["SupplierSKU"].ToString());
}

您只需将文本保存到文件中,并在末尾添加xls。如果需要适当的电子表格功能,则需要使用Excel库:是。但我仍然不能在excel中添加列标题吗?另外,我可以根据该列中的数据调整列吗?