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

时间:2014-05-29 00:11:13

标签: c# console-application export-to-excel

如何添加自定义列标题?

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

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

        }


    }

任何例子都会受到赞赏........................

1 个答案:

答案 0 :(得分:1)

如果您只想在文件的第一行中使用列名,请尝试使用此类

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());
}