我该如何在C#中读写Excel文件? 我已经将Excel Objects Library添加到我的项目中,但是我没有得到足够清晰的描述以访问这些文件。
请帮助我理解。在解释时,请记住我有些新手,但我不是完全的菜鸟。我学习很多,所以我并不完全无知。
我非常喜欢使用EPPlus来执行这类操作。EPPlus是一个库,您可以在项目中引用它并在服务器上轻松创建/修改电子表格。我将其用于需要导出功能的任何项目。
这里有一篇不错的博客文章介绍如何使用该库,但该库本身应该附带一些示例,说明如何使用它。
在我看来,第三方库比微软的COM对象要容易使用得多。建议尝试一下。
using Excel = ClosedXML.Excel;
namespace Excel_Tests
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//create 'workbook' object
var wb = new Excel.XLWorkbook("E:\\test1.xlsx");
//create 'worksheet' object
var ws = wb.Worksheets.Worksheet("Sheet1");
//read cells
var a = ws.Cell("A1").Value;
var b = ws.Cell("B1").Value;
Console.WriteLine(a.ToString());
Console.WriteLine(b.ToString());
//write cells
ws.Cell("F2").Value = 9999999;
ws.Cell("F2").Value = 2.333;
ws.Cell("G2").Value = "This is cell G2";
wb.Save();
}
}
}
您可以使用Excel自动化(基本上是COM基础知识)例如:
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("1.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
object[][] cells
)来读取/写入数据。**Reading the Excel File:**
string filePath = @"d:\MyExcel.xlsx";
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filePath);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range xlRange = xlWorkSheet.UsedRange;
int totalRows = xlRange.Rows.Count;
int totalColumns = xlRange.Columns.Count;
string firstValue, secondValue;
for (int rowCount = 1; rowCount <= totalRows; rowCount++)
{
firstValue = Convert.ToString((xlRange.Cells[rowCount, 1] as Excel.Range).Text);
secondValue = Convert.ToString((xlRange.Cells[rowCount, 2] as Excel.Range).Text);
Console.WriteLine(firstValue + "\t" + secondValue);
}
xlWorkBook.Close();
xlApp.Quit();
**Writting the Excel File:**
Excel.Application xlApp = new Excel.Application();
object misValue = System.Reflection.Missing.Value;
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "ID";
xlWorkSheet.Cells[1, 2] = "Name";
xlWorkSheet.Cells[2, 1] = "100";
xlWorkSheet.Cells[2, 2] = "John";
xlWorkSheet.Cells[3, 1] = "101";
xlWorkSheet.Cells[3, 2] = "Herry";
xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close();
xlApp.Quit();
如果您只需要进行简单的操作并且可以使用 xlsx 格式,那么您可以尝试自己操纵 XML。我已经这样做过,并发现它比解析 Excel 库更快。
还有一些第三方库可以更容易地使用... 并且可以在服务器上使用,而 Microsoft 的库则不能。