将数据导出时,报错,说Application的Save方法无效。用OFFICE2013和WPS均报出相同错误,其他计算机上使用WPS可以成功导出数据,求大神指点。
没有代码,怎么知道。
excel可以直接导入外部数据的,你录个宏看看哪错了
vb.net 的DataGridView 数据导出到excel的例子,我们项目中一直使用的,可以看看有无帮助。
''' <summary>
''' dgv导出至Excel
''' </summary>
''' <param name="Title">表标题</param>
''' <param name="pb">pb</param>
''' <returns></returns>
''' <remarks></remarks>
Shared Function dgvToExcel(ByVal Title As String, ByVal dgv As DataGridView, ByVal pb As ProgressBar) As Boolean
If dgv.Rows.Count = 0 Then Return False
Dim xlApp As New Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim rowIndex, colIndex As Integer
rowIndex = 2
colIndex = 0
xlBook = xlApp.Workbooks().Add
xlSheet = xlBook.Worksheets("sheet1")
xlSheet.Cells.NumberFormatLocal = "@"
Dim Table As DataTable = dgv.DataSource
If Table Is Nothing Then '说明此表为无源的数据表
Table = GetDgvToTable(dgv)
End If
'将所得到的表的列名,赋值给单元格
Dim Col As DataColumn
Dim col1 As DataColumn
Dim Row As DataRow
xlApp.Cells(1, 1) = Title
'exsheet.range(cells, cells).merge()
xlApp.Range(xlApp.Cells(1, 1), xlApp.Cells(1, Table.Columns.Count)).Merge()
xlApp.Cells(1, 1).HorizontalAlignment = 3
For Each Col In Table.Columns
colIndex = colIndex + 1
xlApp.Cells(2, colIndex) = Col.ColumnName
Next
'得到的表所有行(, 赋值给单元格)
pb.Maximum = Table.Rows.Count
pb.Value = 0
For Each Row In Table.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each col1 In Table.Columns
colIndex = colIndex + 1
xlApp.Cells(rowIndex, colIndex) = Row(col1.ColumnName)
Application.DoEvents()
Next
pb.Value += 1
Application.DoEvents()
Next
With xlSheet
.Range(.Cells(1, 1), .Cells(1, colIndex)).Font.Name = "黑体"
'设标题为黑体字
.Range(.Cells(1, 1), .Cells(1, colIndex)).Font.Bold = True
'标题字体加粗
.Range(.Cells(1, 1), .Cells(rowIndex, colIndex)).Borders.LineStyle = 1
'设表格边框样式
'.Range(.Cells(1, 1), .Cells(rowIndex, colIndex)).NumberFormatLocal = "@"
'设置单元格为文本格式
End With
With xlSheet.PageSetup
.LeftHeader = "" & Chr(10) & "&""楷体_GB2312,常规""&10公司名称:" '& Gsmc
.CenterHeader = "&""楷体_GB2312,常规""&""宋体,常规""" & Chr(10) & "&""楷体_GB2312,常规""&10日 期:"
.RightHeader = "" & Chr(10) & "&""楷体_GB2312,常规""&10单位:"
.LeftFooter = "&""楷体_GB2312,常规""&10制表人:"
.CenterFooter = "&""楷体_GB2312,常规""&10制表日期:"
.RightFooter = "&""楷体_GB2312,常规""&10第&P页 共&N页"
End With
xlApp.Visible = True
End Function
C#导出到Excel:
引用 ClosedXML.dll , 代码非常简单:
DataTable dt = SqlHelper.GetDataTableByProc(proc, spArr);
dt.TableName = "Sheet1";
var wb = new ClosedXML.Excel.XLWorkbook();
wb.Worksheets.Add(dt);
wb.SaveAs(filePath);
用SQLServer导出Excel还可以直接用它自带的导入导出向导。