2014-04-13 126 views
27

这就是我想要做的。如何将一些数据写入excel文件(.xlsx)

1.创建Excel文件(.XLSX)C://test/files/work1_4.13.14.xlsx与名称+值(日期)

例如:work1_4.13.14.xlsx

2。将标题设置为文件示例:[名称] [年龄] [城市]。

3.我有3个名单,年龄,城市,我需要填写到excel工作表。

这是我的目标

Name Age City 
Ben 20 xyz 
Jack 25 xyz 
Mike 45 zyx 

任何想法?

+1

显示在格和比使用导出到Excel表格的GridView对于相同的相同数据。 –

+0

接受的答案相当过时,IMO不会对开发人员atm有好处 - 如果您计划使用office.interop.excel,那么您必须将办公室安装在部署的PC中,这是一种不必要的依赖关系+如果您忘记处理,会流血记忆。还有其他的图书馆,你不需要安装Office,而且使用起来非常简单:NPOI,ClosedXml和EPPlus是一些流行的选择,我会让读者根据自己的特殊需求决定哪个是最好的,但是我会全心全意地推荐这三个中最糟糕的部分.interop dll – BKSpurgeon

回答

74

试试这个代码

Microsoft.Office.Interop.Excel.Application oXL; 
Microsoft.Office.Interop.Excel._Workbook oWB; 
Microsoft.Office.Interop.Excel._Worksheet oSheet; 
Microsoft.Office.Interop.Excel.Range oRng; 
object misvalue = System.Reflection.Missing.Value; 
try 
{ 
    //Start Excel and get Application object. 
    oXL = new Microsoft.Office.Interop.Excel.Application(); 
    oXL.Visible = true; 

    //Get a new workbook. 
    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add("")); 
    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet; 

    //Add table headers going cell by cell. 
    oSheet.Cells[1, 1] = "First Name"; 
    oSheet.Cells[1, 2] = "Last Name"; 
    oSheet.Cells[1, 3] = "Full Name"; 
    oSheet.Cells[1, 4] = "Salary"; 

    //Format A1:D1 as bold, vertical alignment = center. 
    oSheet.get_Range("A1", "D1").Font.Bold = true; 
    oSheet.get_Range("A1", "D1").VerticalAlignment = 
     Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; 

    // Create an array to multiple values at once. 
    string[,] saNames = new string[5, 2]; 

    saNames[0, 0] = "John"; 
    saNames[0, 1] = "Smith"; 
    saNames[1, 0] = "Tom"; 

    saNames[4, 1] = "Johnson"; 

    //Fill A2:B6 with an array of values (First and Last Names). 
    oSheet.get_Range("A2", "B6").Value2 = saNames; 

    //Fill C2:C6 with a relative formula (=A2 & " " & B2). 
    oRng = oSheet.get_Range("C2", "C6"); 
    oRng.Formula = "=A2 & \" \" & B2"; 

    //Fill D2:D6 with a formula(=RAND()*100000) and apply format. 
    oRng = oSheet.get_Range("D2", "D6"); 
    oRng.Formula = "=RAND()*100000"; 
    oRng.NumberFormat = "$0.00"; 

    //AutoFit columns A:D. 
    oRng = oSheet.get_Range("A1", "D1"); 
    oRng.EntireColumn.AutoFit(); 

    oXL.Visible = false; 
    oXL.UserControl = false; 
    oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, 
     false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, 
     Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 

    oWB.Close(); 

    //... 
+8

它可以很好地工作,但有没有可能在没有打开Excel的情况下执行它?直接写入文件?因为速度非常慢100k值)..我有一种感觉,这个瓶颈本身就是优秀的 – Lonefish

+0

@ user3458958一个很好的例子,如果头文件II会使用foreach循环来显示,例如从一个Datatable或for循环读取 – MethodMan

+0

有关此答案的更多详细信息,请访问:https ://support.microsoft.com/en-in/kb/302084 – explorer

12

您可以使用ClosedXML

Store中的数据表中的表,你可以导出表通过这个简单的代码片段擅长:

XLWorkbook workbook = new XLWorkbook(); 
DataTable table = GetYourTable(); 
workbook.Worksheets.Add(table); 

您可以阅读ClosedXML的文档,以了解更多信息。希望这可以帮助!

+1

非常适合新数据,但这里的缺点是ClosedXML缺乏智能来更新或替换现有工作表中的数据。常见用例是以模板并将数据应用到它;如果它具有像图表一样的意义,ClosedXML可能会破坏该模板 –

7

希望这里是确切的是我们所期待的。

private void button2_Click(object sender, RoutedEventArgs e) 
{ 
    UpdateExcel("Sheet3", 4, 7, "[email protected]"); 
} 

private void UpdateExcel(string sheetName, int row, int col, string data) 
{ 
    Microsoft.Office.Interop.Excel.Application oXL = null; 
    Microsoft.Office.Interop.Excel._Workbook oWB = null; 
    Microsoft.Office.Interop.Excel._Worksheet oSheet = null; 

    try 
    { 
     oXL = new Microsoft.Office.Interop.Excel.Application(); 
     oWB = oXL.Workbooks.Open("d:\\MyExcel.xlsx"); 
     oSheet = String.IsNullOrEmpty(sheetName) ? (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet : (Microsoft.Office.Interop.Excel._Worksheet)oWB.Worksheets[sheetName]; 

     oSheet.Cells[row, col] = data; 

     oWB.Save(); 

     MessageBox.Show("Done!"); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.ToString()); 
    } 
    finally 
    { 
     if (oWB != null) 
     oWB.Close(); 
    } 
} 
8

有可能写入到一个Excel文件,而无需使用Microsoft.Jet.OLEDB.4.0OleDb打开它。使用OleDb,它的行为就像使用sql写入表一样。

这是我用来创建和写入新的excel文件的代码。没有多余的引用,需要

var connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SomePath\ExcelWorkBook.xls;Extended Properties=Excel 8.0"; 
using (var excelConnection = new OleDbConnection(connectionString)) 
{ 
    // The excel file does not need to exist, opening the connection will create the 
    // excel file for you 
    if (excelConnection.State != ConnectionState.Open) { excelConnection.Open(); } 

    // data is an object so it works with DBNull.Value 
    object propertyOneValue = "cool!"; 
    object propertyTwoValue = "testing"; 

    var sqlText = "CREATE TABLE YourTableNameHere ([PropertyOne] VARCHAR(100), [PropertyTwo] INT)"; 

    // Executing this command will create the worksheet inside of the workbook 
    // the table name will be the new worksheet name 
    using (var command = new OleDbCommand(sqlText, excelConnection)) { command.ExecuteNonQuery(); } 

    // Add (insert) data to the worksheet 
    var commandText = $"Insert Into YourTableNameHere ([PropertyOne], [PropertyTwo]) Values (@PropertyOne, @PropertyTwo)"; 

    using (var command = new OleDbCommand(commandText, excelConnection)) 
    { 
     // We need to allow for nulls just like we would with 
     // sql, if your data is null a DBNull.Value should be used 
     // instead of null 
     command.Parameters.AddWithValue("@PropertyOne", propertyOneValue ?? DBNull.Value); 
     command.Parameters.AddWithValue("@PropertyTwo", propertyTwoValue ?? DBNull.Value); 

     command.ExecuteNonQuery(); 
    } 
} 
0

只要按照下面的步骤:

//启动Excel并得到应用对象。

oXL = new Microsoft.Office.Interop.Excel.Application(); 

oXL.Visible = false; 
相关问题