我使用excel addin应用程序,创建可以将列从一个excel文件复制到另一个excel文件的函数。这是目前为止的代码,但是当我渲染应用程序时,程序会输出一个空白的book.xls文件。
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Workbook xlWorkBook2;
Excel.Worksheet xlWorkSheet;
Excel.Worksheet xlWsheet2;
Excel.Range xlSourceRange;
Excel.Range xlSourceRange1;
Excel.Range xlDestRange;
Excel.Range xlDestRange1;
xlWorkBook = xlApp.Workbooks.Open("C:/../../../../../../../Test.xls");
xlWorkBook2 = xlApp.Workbooks.Open("C:/../../../../../../../Book1.xls");
//~~> Display Excel
xlApp.Visible = true;
//~~> Set the source worksheet
xlWorkSheet = xlWorkBook.Sheets["Sheet1"];
//~~> Set the destination worksheet
xlWsheet2 = xlWorkBook2.Sheets["Sheet1"];
//~~> Set the source range
xlSourceRange = xlWorkSheet.Range["E15"].EntireColumn;
xlSourceRange1 = xlWorkSheet.Range["D15"].EntireColumn;
//~~> Set the destination range
xlDestRange = xlWsheet2.Range["A2"];
xlDestRange1 = xlWsheet2.Range["B2"];
xlSourceRange.Copy(Type.Missing);
xlDestRange.PasteSpecial(Excel.XlPasteType.xlPasteAll,
Excel.XlPasteSpecialOperation.xlPasteSpecialOperationAdd, false, false);
xlSourceRange1.Copy(Type.Missing);
xlDestRange1.PasteSpecial(Excel.XlPasteType.xlPasteAll,
Excel.XlPasteSpecialOperation.xlPasteSpecialOperationAdd, false, false);
}
我不确定如何跟踪错误,因为我目前是新手用户 - 使用excel库。任何进一步的援助将是最受欢迎的 感谢
答案 0 :(得分:1)
朋友请使用下面的代码,使用此查询的列名实例“从sheetName中选择列名”
static void Main(string[] args)
{
string sourceFileName = @"C:\Test.xls";
DataTable dataTable = loadSingleSheet(sourceFileName, "Employee");
dataTable.Columns.Add("COLUMN_A");
dataTable.Columns.Remove("COLUMN_B");
}
private static OleDbConnection ReturnConnection(string fileName)
{
return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}
private static DataTable LoadSingleSheet(string fileName, string sheetName)
{
DataTable sheetData = new DataTable();
using (OleDbConnection conn = ReturnConnection(fileName))
{
conn.Open();
OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select columnname from [" + sheetName + "]", conn);
sheetAdapter.Fill(sheetData);
}
return sheetData;
}
private static void UpdateSingleSheet(string fileName, string sheetName, DataTable dataTable)
{
using (OleDbConnection conn = ReturnConnection(fileName))
{
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand("SELECT columnname FROM [" + sheetName + "]", conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Update(dataTable);
}
}
我这样称呼它:
string destinationFileName = @"C:\TestNew.xls";
UpdateSingleSheet(destinationFileName, "Employee", dataTable);