我已经知道如何使用openfiledialog保存在excel中。但我想要发生的是,当我保存另一个文件时,我希望它保存在我现有的文件中,但在另一张表中。你能帮助我吗?
这是我保存的代码
Public Sub saveExcelFile(ByVal FileName As String)
Dim xls As New Excel.Application
Dim sheet As Excel.Worksheet
Dim i As Integer
xls.Workbooks.Add()
sheet = xls.ActiveWorkbook.ActiveSheet
Dim row As Integer = 1
Dim col As Integer = 1
For Each item As ListViewItem In ListView1.Items
For i = 0 To item.SubItems.Count - 1
sheet.Cells(row, col) = item.SubItems(i).Text
col = col + 1
Next
row += 1
col = 1
Next
xls.ActiveWorkbook.SaveAs(FileName)
xls.Workbooks.Close()
xls.Quit()
End Sub
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
Dim saveFileDialog1 As New SaveFileDialog
saveFileDialog1.Filter = "Excel File|*.xlsx"
saveFileDialog1.Title = "Save an Excel File"
saveFileDialog1.ShowDialog()
If saveFileDialog1.FileName <> "" Then
saveExcelFile(saveFileDialog1.FileName)
End If
MessageBox.Show("Record Saved!")
End Sub
答案 0 :(得分:0)
使用NPOI导出为Excel。您可以使用NPOI指定工作表。有关详细信息,请参阅documentation
您也可以使用Officehelper
修改强>
使用此示例代码使用NPOI创建Excel工作表。它只是一个示例代码。您需要参考文档以获取更多详细信息。
List<OrderViewModel> orderViewModelList = SelectOrders();
//Add Column title
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
HSSFSheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
sheet1.CreateRow(0).CreateCell(0).SetCellValue("Order No");
sheet1.CreateRow(0).CreateCell(5).SetCellValue("Price");
//check for if device exist for saving
if (orderViewModelList.Count() > 0)
{
//Convert to csv class type
int i = 0;
foreach (var item in orderViewModelList)
{
HSSFRow enqRow = sheet1.CreateRow(i + 1);
enqRow.CreateCell(0).SetCellValue(item.OrderId);
enqRow.CreateCell(5).SetCellValue(( item.OrderAmount));
i++;
}
}
MemoryStream file = new MemoryStream();
hssfworkbook.Write(file);
byte[] Data = file.GetBuffer();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=OrderReport.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
Response.BinaryWrite(Data);
Response.End();
如果要将新工作表附加到现有Excel工作表 refer this example